I have some confusion about using Object.assign
for React and Redux.
I read this article.
It says ES6 Does not supported by all browsers but I have started using it.
I have two questions:
Object.assign
?My Code
export const selectDiameter = (scaleData, size) => { return { type: SELECT_DIAMETER, payload: Object.assign({}, scaleData, { diameter: Object.assign({}, scaleData.diameter, { selected_tube_diameter: size, is_clicked: true, audio: Object.assign({}, scaleData.diameter.audio, { is_played: true }) }) }) } }
What is the alternative for the above code?
The difference is that Object. assign changes the object in-place, while the spread operator ( ... ) creates a brand new object, and this will break object reference equality.
Spread operator could be use to simplify passing react props down to a component. In react redux and reducer functions, spread operator are applied to compute new state without mutating state.
Since one of the core principles of Redux is to never mutate state, you'll often find yourself using Object. assign() to create copies of objects with new or updated values. For example, in the myApp Object. assign() is used to return new state with updated property qty.
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.
Redux docs recommends you to use the spread operator approach instead of the Object.assign
As per the docs:
An alternative approach is to use the object spread syntax proposed for the next versions of JavaScript which lets you use the spread (...) operator to copy enumerable properties from one object to another in a more succinct way. The object spread operator is conceptually similar to the ES6 array spread operator
The advantage of using the object spread syntax becomes more apparent when you're composing complex objects
Using the Spread operator syntax
export const selectDiameter = (scaleData,size) => { return { type: SELECT_DIAMETER, payload: {...scaleData, diameter: { ...scaleData.diameter, selectedTube: size, isClicked: true, audio: { ...scaleData.diameter.audio, isPlayed: true } } } } }
It still uses ES6. See the Redux docs for more info on configuring your code for the same
However when you are dealing with the nested data. I prefer to use immutability-helpers
For your code it will be like
import update from 'immutability-helpers'; export const selectDiameter = (scaleData,size) => { return { type: SELECT_DIAMETER, payload: update(scaleData, { diameter: { selectedTube: { $set: size}, isClicked: { $set: true}, audio: { isPlayed: {$set: true} } } }) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With