When I click the “delivered” button, the state of newQunatity doesn’t update immediately. But after reloading the page, it updates the state of newQuantity. How will I update the state of newQuantity immediately?
// SingleBook.jsx
const loadedBook = useLoaderData();
// console.log(loadedBook);
const { _id, name, image, description, price, quantity, supplier, sold } = loadedBook;
const [newQuantity, setNewQuantity] = useState(quantity);
const handleDelivered = (_id) => {
fetch(`http://localhost:5000/books/${_id}/delivered`, {
method: "POST",
headers: {
"content-type": "application/json"
},
// body: JSON.stringify({})
})
.then(res => res.json())
.then(data => {
console.log(data);
setNewQuantity(newQuantity - 1);
console.log("The value of newQuantity:", newQuantity);
})
}
// Use useEffect to log newQuantity whenever it changes
useEffect(() => {
console.log("Updated newQuantity:", newQuantity);
}, [newQuantity]);
<div className="card-actions justify-end">
<button onClick={() => handleDelivered(_id)} className="btn btn-primary">Delivered</button>
</div>