I am not getting the point of using ...in ...state. When I have watched a tutorial of react redux they mentioned that it is destructuring of state variable but can you explain me the point mentioned .
export const productreducer=(state=initialstate,{type,payload})=>{
switch(type)
case ActionTypes.SETPRODUCTS:
return{...state,...payload}; //here I have a doubt
default:
return state
}
};
So {...} refers to spread or expand out the iterable elements, Lets take an example, you cannot change the state directly in the redux store and therefore you need to make a copy and append the new payload to the state and return the state.
state={ x:1, y:2 } payload={ y:5 , z:6 }
{...state, ...payload} // { x: 1, y: 5, z: 6 }
This will update the old state to the new state.
Generally, assume you have
const a = { foo: 1, bar: 2 }
then the following two are equivalent:
return { foo: a.foo, bar: b.bar }
and
return { ...a }
so essentially, ... copies over all the elements from the old object into a new object.
That said, modern Redux doesn't do this. Modern Redux also does not do switch..case reducers, ACTION_TYPES or connect. You might have been following a very outdated tutorial.
I would really recommend you to follow the official Redux Essentials tutorial that will teach you modern Redux from the beginning - it's much safer against accidental errors and only a fourth of the code.
It's Spread syntax. In your case, it gets all key: value pairs from objects and combines them into a new object. Hope with snippet it will be more clear
const state = {a: 1, b: 2}
const payload = {c: 3, d: 4}
const result = {...state, ...payload}
console.log(result)