3

I'm creating a web application using React 16.10 and when I try adding an element to an empty array using Array.concat(), at first it returns an empty array and after the second try it returns the extended array.

The reasons why I'm not using Array.push():

Here is the code:

const [pizzas, setPizzas]= useState([]);

const addPizza = (type, size, dough, price) => {
    setPizzas(pizzas.concat([{type, size, dough, price}]));
    console.log(pizzas);
}

The addPizza function is triggered when the button is clicked. When I click it the first time, console returns [], but when I click it the second time, it returns the extended array: [{...}].

The weird thing is that when I try doing something similar in the browser's console, it works correctly:

const a = [];

a.concat({name: 'James'}); // returns [{name: 'James'}]

2 Answers 2

4

.concat() doesn't modify an Array; it returns a new Array containing the concatenation. Thus, this line does set the pizzas state in the next render to an array with the new item:

setPizzas(pizzas.concat([{type, size, dough, price}]));

...because it sort of translates to this:

const newPizzas = pizzas.concat([{type, size, dough, price}]);
setPizzas(newPizzas);

...but the local pizzas variable you're logging is not modified. The next time useState is called, pizzas will have the new value, however.

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

2 Comments

set value is assigning in next useState call, how can i set value in real-time?
You would have to use let instead of const and assign to the variable in addition to doing set call. That is not the typical way that React apps are built, though. Normally you just let the change reflect in the next render and use things like useEffect to respond to state changes with procedural logic.
0

setting state in React is asynchronous. When you call a setter obtained from useState the guarantee you have is that in the future the function will be called with the new updated state.

It does not update the existing reference (to pizzas) - rather it calls the function with the new one.

That's just how state works in react - presumably to create a pretense of immutability inside a render.

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.