in my react app, there is a setting "page" with different setting categories with respective setting items. Hence, I need a nested state (?) to avoid having lots of properties called "category1-id", "category1-element1-id" etc.
That looks as follows:
    this.state = {
          categories: [
            {
              id: 1,
              label: "Category 1",
              elements: [
                { id: 1, label: "Option 1", selected: true },
                { id: 2, label: "Option 2", selected: false },
              ],
            },
            {
              id: 2,
              label: "Category 2",
              elements: [
                { id: 1, label: "Option 1", selected: true },
                { id: 2, label: "Option 2", selected: false },
                { id: 3, label: "Option 3", selected: false },
              ],
            },
          Other property: "...",
To update the state, I need a deep copy instead of a shallow one. How do I achieve this? Is there any other alternative solution?
Using
let categories = [...this.state.categories];
categories = JSON.parse(JSON.stringify(categories));
doesn't work (error) and is not really fail-proof.
Since this is the only nested state in my app, I'd like to avoid using lodash & co.
The function called when clicking on the option looks like this. But this modifies the state directly.
  handleOptionSelect = (categoryId, option) => {
    const categories = [...this.state.categories];
    // FIND INDEX OF CATEGORY
    const category = categories.find((category) => category.id === categoryId);
    const indexCat = categories.indexOf(category);
    // //FIND INDEX OF ELEMENT
    const elements = [...category.elements];
    const indexEle = elements.indexOf(element);
    //MODIFY COPIED STATE
    const e = categories[indexCat].elements[indexEle];
    e.selected = e.selected ? false : true;
    // //SET NEW STATE
    this.setState({ categories });
  }
Thank you very much for your help! I am still at the beginning trying to learn React and JS :)
 
    