the spread operator in Redux reducer

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'})

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


Assume that your state structure looks like this:

const initialState = {
    DateSucess: ' ',
    DateFailure: ' '
}

Well then, with that state, now we write a reducer and..

The reducer is a pure function that takes the previous state and an action, and returns the next state.

In the reducer, we make some calculation and return the next state. Keeping in mind that, we don't mutate the state. We create a copy with Object.assign().

Object.assign(state, { DateSucess: action.payload}) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. Like this:

return Object.assign({}, state, { DateSucess: action.payload})    

You can also enable the object spread operator proposal to write { ...state, ...newState } instead. In your case, it will look like:

return {...state, DateSucess: action.payload}

For more information: https://redux.js.org/basics/reducers