When I click on this button:
<Button
onClick={(e) => {
addToCard(item);
handleprisma();
}}
>
add to cart
</Button>
This function wants to add the item to my card:
const addToCard = (item) => {
const newCard = {
fff: "1",
ddd: "2",
aa: "3",
dfdfdf: "4",
asdf: "5",
teest: "6",
};
context.setcount(context.count + 1);
context.setcard((prev) => [...prev, newCard]);
};
And this one wants to send it to my database:
const testtt= context.card;
async function handleprisma() {
const res = await axios.post('/api/Me', {
testtt,
});
console.log(res.data);
}
And by default, the value of the card is []
so I think when I click on the button it does not run the addToCard
! But on the second click in the database, I see that the array that should have been created on the first click is there, and when I click again, I see that the array that should have been created on the second click is there.
I solved this problem with this:
useEffect(() => {
if (context.card.length !== 0) {
handleprisma();
}
}, [addToCard]);
So when I have 1 item in my card and if I refresh the page, 3 or 4 new copies of the same thing will be created in the database, so how can I just stop getting those copies?
I wanted to use useCallback
to solve this problem so I converted that useEffect
to:
useCallback(() => {
if (context.card.length !== 0) {
handleprisma();
}
console.log('sfd');
}, [addToCard]);
and to:
useCallback(() => {
if (context.card.length !== 0) {
handleprisma();
}
console.log('sfd');
}, [context.card]);
But why is nothing happening when I click on the button?
Via Active questions tagged javascript - Stack Overflow https://ift.tt/74UcPJO
Comments
Post a Comment