Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
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]]);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.