1

Short question is: what does the line

return { ...state, all: action.payload.data };

do? (particularly with the all: part).

If you don't use ES6, and state has

  1. 2 properties like below
  2. 10 properties instead of 2
  3. unknown number of properties

then how would it be written?


Details: it is part of React / Redux. In a reducer function, given a previous state and action, it does:

const INITIAL_STATE = {
  all: [],
  post: null
};

export default function(state = INITIAL_STATE, action) {

  switch(action.type) {
    case FETCH_POSTS:
      return { ...state, all: action.payload.data };
    default:
      return state;
  }
}
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

4

Technically, this is the same as calling:

return Object.assign({}, state, {all: action.payload.data});

It means that the resulting object:

  1. is not the original object
  2. it contains all properties from state
  3. it contains a new value for property all.
Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

What return { ...state, all: action.payload.data }; does is to destructure the state to obtain all the properties in it and then return the object by modifying all only the object with key all

suppose in your case

state={
  all: [],
  post: null
};

then

...state will return you all:[], post:null as separate values. So with { ...state, all: action.payload.data } you are setting the value of all to be action.payload.data and returning the entire values wrapped as an object. In your case if action.payload.data = ["hello", "world"], it will return

{
    all: ["hello", "world"],
    post: null
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400