Hello I was trying to store some data in my array and I did try allData.push(Data1, Data2, Data3)
but it said .push
was not a function and it also didn't let me just allData(Data1, Data2, Data3)
, w/e data I get it overrides the previous one. I also tried allData(Data1 Data2 Data3)
finally I try something someone suggested me setAllItems([LibrosID1, LibrosID2, LibrosID3])
but it ended up looping and bringing an error:
My "closest" attempt so far has being this one :
useEffect(() => {
let x = 0;
LibrosID1.map((i) => {
x = i.precio
})
LibrosID2.map((i) => {
x = i.precio
})
LibrosID3.map((i) => {
x = i.precio * i.necesita
})
setSubTotal(parseFloat(x).toFixed(2))
setAllItems([LibrosID1, LibrosID2, LibrosID3])
console.log(allItems)
}, [LibrosID1, LibrosID2, LibrosID3]);
What I do not understand is that I'm doing exactly the same with setSubTotal
but that doesn't give me any kind of issue and it doesn't make sense that setAllItems
give me an error and loop otherwise setSubTotal
would loop and error as well right? so what am I doing wrong?
Any tips, documentation and help is welcome.
If you require the whole code let me know but I doubt is required.
Update - Edit: So I fixed the loop bit and separated the code so people don't get confuse, but now I'm having a delay when I try to get data
useEffect(() => {
setAllItems([LibrosID1, LibrosID2, LibrosID3])
console.log(allItems)
}, [LibrosID1, LibrosID2, LibrosID3]);
When I click the checkbox I get to see how the data is getting parse on LibrosID1 but it says 0 on allItems:
When I click the checkbox again it says 12, even though I just "uncheck" them.
I don't get it! very frustrated atm
CodePudding user response:
You can try the following:
let librosID1 = ["a"];
let librosID2 = ["b"];
let librosID3 = ["c"];
const [allItems, setAllItems] = useState(null);
const [subTotal, setSubTotal] = useState();
useEffect(() => {
setAllItems([...librosID1, ...librosID2, ...librosID3]);
}, []);
console.log(allItems)
The spread operator is used to display or combine all elements from objects or arrays.
References:
Spread syntax (...). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax. (Accessed 28 September, 2021).