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:
- Is it the right decision to continue with
Object.assign
? - What is the alternative?
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?
Ok may be I was not really right but this is from Dan Abramov (redux creator)
Redux docs recommends you to use the spread operator approach instead of the
Object.assign
As per the docs:
The advantage of using the object spread syntax becomes more apparent when you're composing complex objects
Using the Spread operator syntax
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
The alternative to the code you posted is using object spreading:
I have also shortened the body of the arrow function in your code to simply returning the object.
You can use the object rest spread syntax by using the Babel plugin transform-object-rest-spread.
Install it like this:
Configure its use in your .babelrc like this:
Object spread is ES7 syntax, render supported by Babel, Object.assign() is ES6 syntax, it not support in some browser. That's why you should use Object spread instead of Object.assign()