Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get previous and current state in Redux's reducer

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading