0

I'm trying to pushing a new object (after clicking a button) into my stated Array, my initial array has 25 cocktails.I want to push one, simply, first of all, this is my code about the insert.

console.log(drinks,"First, before pushing");
setDrinks([...drinks, {strPicture: null, strDrink: 'Vodka', strAlcoholic: 'Alcoholic', strCategory:'Cacharro'}]);
console.log(drinks,"Second, After pushing");

The first console log return an array with length 25, next i use my setDrinks, adding the previous drinks and the new one. But the next console log returns an array with length 25, the same array of the first console log.

The next time i click my button it give me, the array with length 26, but i need to show on the first click, not on the second.

I tried many things like...

setDrinks((drinks) => [...drinks, {strPicture: null, strDrink: 'Vodka', strAlcoholic: 'Alcoholic', strCategory:'Cacharro'}]);

The only way that it have worked is with drinks.push but i read that is a very bad idea.

I'm using next js.

Thanks

  • setState is not an async function, that's why it prints the previous length. – Rahul Sharma Jun 28 '21 at 09:07
  • State updates are asynchronous. When you call `setDrinks`, that will (eventually) make React call your component again, and you'll see the new value come back from `useState`. – T.J. Crowder Jun 28 '21 at 09:07

0 Answers0