Search code examples
reactjssetstate

React - setting state with imported data keeps getting updated


I am importing an array of data like

import { menuData } from '../../data/menu-data';

data being:

export const menuData = [
  { id: 'all', title: 'Select all', icon: '', selected: false },
  { id: 'overview', title: 'Overview', icon: 'user-check', selected: false },
  {
    id: 'about',
    title: 'About',
    icon: 'info-circle',
    selected: false,
    partSelected: false,
    
  }
];

I then initialise some state in my parent component like:

  const [downloadMenu, setMenuState] = useState([...menuData]);

I pass "downloadMenu" state to my child compionent and absorb it as a prop and then create a copy of it which gets mutated i.e.

 const updatedMenu = [...downloadMenu];

i then call this function which is in the parent and is passed down as a prop to the child component

 onMenuChange(updatedMenu);

 const handleMenuChange = (menuState) => {
    setMenuState(menuState)
  }

This works but when i try and reset the state to the initial menuData it doesnt work. MenuData is getting mutated aswell. Why is this?

I am calling this again - setMenuState([...menuData]); but menuData is the same as the downloadMenu state.


Solution

  • Using ... only creates a shallow copy - a new list is created, but the items inside it remain the same. The objects in the list aren't copied, but remain as a reference to the original objects in menuData.

    The solution is either to create a new object when you change menuData or create a deep copy. A deep copy can be created using JSON - JSON.parse(JSON.stringify(menuData)) or a library like lodash - _.cloneDeep(menuData).