0

this is my reducer function :

export default (posts = [], action) => {
  switch (action.type) {
    case FETCH_ALL:
      return action.payload;
    case LIKE:
      return posts.map((post) => (post._id === action.payload._id ? action.payload : post));
    case CREATE:
      return [...posts, action.payload];
    case UPDATE:
      return posts.map((post) => (post._id === action.payload._id ? action.payload : post));
    case DELETE:
      return posts.filter((post) => post._id !== action.payload);
    default:
      return posts;
  }
};

in

case CREATE:
      return [...posts, action.payload];

what i have understood so far is that reducer function gets old state and new state . old state is represented by 'posts' and new state is represented by 'action.payload' ...now what i do not understand is that what is [...posts, action.payload] ?

what are those three dots ? why there are square brackets ? what does reducer function returns ? what is happening here ? i am a java programmer , i can't understand anything here

  • 3
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – Chellappan வ Feb 18 '21 at 04:44
  • 1
    Your understanding is not quite right. The reducer gets the old state and the action and it returns the new state. The new state that you are returning in this particular case is a new array which copies all of the posts from the old state and adds the payload of the action as a new post at the end of the array. This is done with the spread syntax explained on the linked doc. – Linda Paiste Feb 18 '21 at 05:44

1 Answers1

1

i have understood everything .

reducer function is getting two parameters (posts = [], action) :

first one is old state and the second parameter is action object which includes type and new data ...this reducer function returns a new state by adding my new data into old state

in this

case CREATE:
      return [...posts, action.payload];

these ...three dots are spread syntax which can be understood completely by going to the following link given by chellappan in comment section :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

[]square brackets denote an array which is our new state.

  • 2
    Please also note that in modern redux, you would not need to write immutable logic in reducers if you use `createReducer` and `createSlice`: https://redux.js.org/tutorials/fundamentals/part-8-modern-redux In general, you are writing a quite old style of redux there and are probably following an outdated tutorial. Please follow https://redux.js.org/tutorials/index – phry Feb 18 '21 at 07:24