1

I want to update list with React.

List I have:

export const arrList = [
  { title: '', elements: []  },
  { title: 'a', elements: ['aaa',  ]  },
  { title: 'b', elements: ['bbb',  ]  },
];

const [poreikiai, setPoreikiai] = useState(arrList);

And now, I want to append to first array element: elements { title: '', elements: [] }

I something like this:

{ title: '', elements: ["firstElement"] }

how can I do it?

I understant that I need to use setPoreikiai but I cant figure out sintax;

Something like:

    setPoreikiai(prevState => { 
      return {...prevState, ...newValue};
    });```

1 Answer 1

1

Deeply clone your way into the data structure and add the new item at the end:

setPoreikiai(prevState => {
  const prevClone = [...prevState];
  
  prevClone[0] = {
    ...prevClone[0],
    elements: [...prevClone[0].elements, "secondItem"]
  };
  
  return prevClone;
});

It's important that you create copies all the way down to the desired level of state so that you do not accidently mutate any values by reference. Any directly mutated data can become out of sync with other effects and memoised components which might accept them as dependencies.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.