Ad

Best Practices For Mutable | Immutable Objects

- 1 answer

Should we use the first way or second way to update the settings object in the state? Which one is the best practice for the mutable | immutable concept?

state = {
  settings: {
    at: [],
    // other keys
  }
}


addHour = () => {
    const { settings } = this.state;

    const time = moment();
    time.set({ minutes: 0, seconds: 0 });

    // First Way
    settings.at.push(time);
    this.setState({ settings });

    // Second Way
    const new_settings = {
        ...settings
        at: [...settings.at, time]
    }
    this.setState({ settings: new_settings });
};
Ad

Answer

The code

const { settings } = this.state;

this isn't making any copy it's just an reference and when you do settings.at.push(time); you're actually mutating original object

let state = {
  settings: [1,2,3]
}
let {settings} = state
settings.push(4)

console.log(settings)
console.log(state)

If your settings array is always one level deep you can use spread operator otherwise you can use JOSN.parse(JOSN.stringify()) to create a deep clone

let state = {
  settings: [1, 2, 3]
}
let settings = [...state.settings]
settings.push(4)

console.log(settings)
console.log(state)

Ad
source: stackoverflow.com
Ad