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():
- it returns the lenght of the extended array
- "Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable."
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'}]