Home > Software design >  State destructuring inside Redux Reducers
State destructuring inside Redux Reducers

Time:10-08

I've a basic todo application, with a Todo Reducer which overlooks addtodo, deleteTodo and other such operations. In the Todo Reducer I understand why the spread operator is used i.e ...state.todos, but I don't understand why ...state is done before that. The Todos, state which is returned from useSelector displays the same todos(i.e an array of todos), even without ...state, so what actual purpose does the ...state serve?

const initialData = {
  todos: [],
};

const todoReducer = (state = initialData, action) => {
  switch (action.type) {
    case "ADD_TODO":
      const { id, data } = action.payload;
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            id,
            data,
          },
        ],
      };
    default:
      return state;
  }
};

export default todoReducer;


CodePudding user response:

In your case the ...state isn't doing anything and if you will only ever have a todos state wont be doing anything but it if you later were to add more data to your state that state would be lost whenever a todo is added. So this is done so that in the future you can add more data to your state without having to update your add todo reducer

CodePudding user response:

In your case, there is a single property (todos) in the initial state that's why it makes no difference. If there were more properties then the difference would be understood. An example will make it clear.

let your initial state is

const initialData = {
  todos: [],
  isLading: false,
  isSuccess: false,
  isError: false,
};

Now if you return from reducer like

return {
        todos: [
          ...state.todos,
          {
            id,
            data,
          },
        ],
      };

your todos will be updated but other properties like isLading: false, isSuccess: false, isError: false will be lost from the state because here we return only todos. We know the store saves only the return value as the new state.

  • Related