Home > front end >  Mutation error when saving redux store. All copied and saved
Mutation error when saving redux store. All copied and saved

Time:03-28

First of all, in the page, the data object is changed with usestate and the screen is drawn! Save the scroll value and data when leaving the page to remember the scroll value on the page. As a result of the confirmation, the changed value is saved, but when I come back, this error keeps popping up.

const mainPageCopy = { ...store.mainPage };
mainPageList.forEach(function (value, index) {
  mainPageCopy.list[index] = value;
  mainPageCopy.scroll = document.querySelector(".body").scrollTop;
});
dispatch({ type: "mainPage/set", payload: mainPageCopy })
router.push(`/product/${value.product_seq}`);

This is not even saved to the store

enter image description here

CodePudding user response:

Your problem is one relating to shallow copies. This code...

const mainPageCopy = { ...store.mainPage };

creates a shallow copy of store.mainPage. Since the list property is an array, the copy will reference the same object in the store. Making changes to them in the forEach() loop is what's triggering the error.

Try this instead

const mainPageCopy = {
  ...store.mainPage,
  scroll: document.querySelector('.body').scrollTop,
  list: [
    ...mainPageList, 
    ...store.mainPage.list.slice(mainPageList.length),
  ],
};

dispatch({ type: "mainPage/set", payload: mainPageCopy });

This replaces the first elements of list with all the elements in mainPageList, leaving the rest of store.mainPage.list as-is. There was also no need to assign scroll within a loop.

  • Related