I am trying to understand what does spread operator do in Redux state?
I went through this question Purpose of the Spread syntax in React-Redux Reducers but wasn't convince with Answer for some reason.
Can someone please explain me in very simple terms why do we do something like this
case WHATEVER:
return {
...state,
DateSucess: action.payload,
Instead of just
case WHATEVER
return {
DataSucess: action.payload
The spread operator does the same as in ES6, is still the same behaviour (check the MDN docs).
About the motivation to use the ...state the idea is simple: Keep the old state and add or overwrite the DateSucess property.
So let's say:
const state = {foo: 'bar', DateSucess: 'oldDateSuccess', zip: 'zap'}
If you don't use spread the new value of state would be only DateSucess and you would lose the foo and zip value, using spread you are just overwriting DateSucess keeping the rest of the value untouched.
This spread would be equivalent to the following with Object.assign
return Object.assign(oldState, {DateSucess: 'newDateSucess'})
If you are using react and asking about react-redux, here might be the answer for you-
We shouldn't mutate a state inside the reducers. With spread operator, we make a copy of the previous state and update the copy of it. So that, we aren't mutating our prev state and at the same time, updating it. This is the function of spread operator.
Now, another question may arise. Why we can't mutate in reducers. Well that's a 'react' thing to me. React creates virtual dom for handling manipulations of doms. If you alter the internal state, the sync of dom and virtual dom may break and things will go bad.
Hope this description helps you.
Spread operator simply return copy of array or obj associated with is. Look into example below
const abc = {
'first_key':1,
'second_key':2,
}
const newObj={...abc} //will COPY abc
const newObjWithNewKey = {...abc, 'first_key':'01 first','new_key':'007'} // will COPY abc and value of first_key will be replaces with new value as it exists. will add new keyvalue pair new_key.
console.log("abc",abc,"newObj",newObj,"newObjWithNewKey",newObjWithNewKey)
Now in redux if you just return new payload
then you will lose other state values.
but if you use ...
means you tell js that copy existing state and update values of specified keys
if there is no key then add new one
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