Working with State and Responding to Events in React - How Do You Update Arrays in State?

Tell us what’s happening:

function ItemsList() {
  const [items, setItems] = useState([
    { id: 0, name: "Item 1" },
    { id: 1, name: "Item 2" },
    { id: 2, name: "Item 3" },
  ]);

  const addItem = () => {
    const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` };
    setItems((prevItems) => [...prevItems, newItem]); // Creates a new array

wouldnt you want to set the id without the +1? It would set the next item to id: 4, item 4, but the id list start with 0, and the item name with 1.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0

Challenge Information:

Working with State and Responding to Events in React - How Do You Update Arrays in State?

1 Like

I looked this up and it said the same thing, but the example used the ternary operator ?.