I am trying to update the values in my order hook. However, the values do not seem to be updating. I am fairly new to React and am not sure what I am doing wrong here. Any Ideas?
Here is my code:
const [order, setOrder] = useState({
specBurger: "",
protein: "",
bread: "",
toppings: "",
sides: "",
drinks: "",
price: 0.00
})
const navigate = useNavigate();
const update = () => {
setOrder((prev) => ({...prev,
specBurger: specItemsString,
protein: proteinItemsString,
bread: breadItemsString,
toppings: toppingsItemsString,
sides: sideItemsString,
drinks: drinkItemsString,
price: price.toFixed(2),
}));
}
const processOrder = async (e) =>{
e.preventDefault();
update();
try{
await axios.post('http://localhost:8800/ordered', order);
navigate("/pages/Confirmation");
}catch(err){
console.log(err);
}
}
I have tried not doing an update()
function and just updating the values inside the processOrder()
but that still didn’t work.
I also tried updating the values without using the (prev) => ({...prev,
That did not work either.
2
Answers
The issue I was having was that I was calling the
update()
function and that would work fine, but useStates may take time to fully process the changes. This meant thataxios.post
was being called beforeorder
was successfully changed. The solution I found was to use a useEffect in order to automatically trigger when order or navigate changed or when I clicked a button.Here is my solution:
if you update your useEffect like:
i.e. removing the buttonClicked from the dependency array. This change will call the process order function only when order is fully updated. Also keep the if condition inside useEffect.