Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the spread operator in Redux reducer

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
like image 971
anny123 Avatar asked Oct 08 '18 12:10

anny123


3 Answers

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'})
like image 54
FabioCosta Avatar answered Oct 05 '22 16:10

FabioCosta


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.

like image 25
shuhat36 Avatar answered Oct 05 '22 18:10

shuhat36


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

like image 38
Revansiddh Avatar answered Oct 05 '22 18:10

Revansiddh