luckydev
luckydev

Reputation: 1

How do I add an object to the end of the array?

How do I add an object to the end of the array?

I am trying to do this, but I end up with an object with one element:

  const [wokSummary, setWokSummary] = useState({
    wok: null
  });

  const onAdded = item => {
    const arr = [{ ...wokSummary.wok, item }];
    setWokSummary({
      wok: arr
    });
  };

Upvotes: 0

Views: 37

Answers (2)

SomoKRoceS
SomoKRoceS

Reputation: 3043

Remove the {} brackets that are inside the list brackets []:

  const [wokSummary, setWokSummary] = useState({
    wok: null
  });

  const onAdded = item => {
    const arr = [...wokSummary.wok, item];
    setWokSummary({
      wok: arr
    });
  };

Your item is the new object, and it is being appended as an element of the list. ...wokSummary.wok spreads wokSummary.wok elements, each element contains an object.

Upvotes: 0

Murat Karagöz
Murat Karagöz

Reputation: 37594

You are creating one single object, simply remove the object assignment e.g.

const [wokSummary, setWokSummary] = useState({
    wok: []
  });

const arr = [ ...wokSummary.wok, item ];

And you have do initialize wok with an empty array.

Upvotes: 1

Related Questions