mercredi 17 novembre 2021

How to push a element in usestate in an array [duplicate]

I am trying to make a shapping cart app and I ran into this problem: I want to push an element into the array but before I already have a array which was from a api if you do not get what I mean why not take a look at the code?

code:

//... react stuff
let[items, setItems] = useState();
setItems([{id:"1kajb2j3h",price:"$450.99",item:"stuff..."},{id:"1kajb2j3h",price:"$450.99",item:"stuff..."}]);

function pushItem(item/*this item is:{id:"1kajb2jsdfasd3h",price:"$459.99",item:"stuff2..."}*/){
//Wanted output: [{id:"1kajb2j3h",price:"$450.99",item:"stuff..."},{id:"1kajb2j3h",price:"$450.99",item:"stuff..."},{id:"1kajb2jsdfasd3h",price:"$459.99",item:"stuff2..."}]
}

//Other stuff:
//....

I have tried to append it with: setItems([...items, newItem]) but this will give me one array and an element outside of the array.

if anyone can help I would greatly appreciate it. Thanks!




Aucun commentaire:

Enregistrer un commentaire