Home > Enterprise >  Get previous and current state in Redux's reducer
Get previous and current state in Redux's reducer

Time:12-07

I start to study Redux. In my app i have a button. I push in this btn and get an object. This object income to reducer in action.payload. Object change everytime, when i push in the button. How i can save all previous state in reducer, and add the current state? To make something like that:

 if (action.type === "ADD_ITEM") {
        return {
          items: [all previous state,   current state],
        };
      }

All code in reducer

const initialState = {
  items: [],
};

const basket = (state = initialState, action) => {
  if (action.type === "ADD_ITEM") {
    return {
      items: [action.data],
    };
  }
  return state;
};

export default basket;

CodePudding user response:

If you want to append new data into an array you can shallow copy the existing state array and append the new data to the end.

const initialState = {
  items: [],
};

const basket = (state = initialState, action) => {
  if (action.type === "ADD_ITEM") {
    return {
      ...state,         // shallow copy existing state
      items: [
        ...state.items, // shallow copy existing items
        action.data,    // append new data
      ],
    };
  }
  return state;
};

CodePudding user response:

You can access the prev value before updating it (and you can save it), and as you know you can update it with an action

  • Related