Reputation: 69
I am trying to add the values of an array by using useState inside an array.map but the values are not updating
function App() {
const [ingredients, setIngredients] = useState([]);
const getIngredients = (data) => {
data.map((item, i) => {
console.log(data[i]);
setIngredients([...ingredients, data[i]]);
// setIngredients([...ingredients, item]); <- Also doesnt work
console.log(ingredients);
});
Console.log(data)
(26) ["Product", "Information↵NUTELLA", "HAZELNUT", "SPREAD", "↵Total:", "↵aty:", "↵BARILLA", "SPAGHETTI", "Z↵Total:", "↵CLASSICO", "CRMY", "ALFERO", "DI", "ROMA", "PENNE", "RIGATE", "PASTA", "↵Order", "Summary↵item", "Subtotat", "↵Sales", "Tax", "Total:", "", "↵", Array(0)]
console.log(ingredients);
[]
console.log(items);
Lists out all the items one after the other
Upvotes: 0
Views: 1230
Reputation: 800
setState is asynchronous so it doesn't guarantee an updated state from before, so pass a function to setState to make it work.
setIngredients((ingredients) => [...ingredients, data[i]]);
Upvotes: 2