Ad
Best Practices For Mutable | Immutable Objects
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad