const [product, setProduct] = useState({});
useEffect(() => {
const url = `http://localhost:5000/product/${id}`;
fetch(url)
.then(res => res.json())
.then(data => setProduct(data))
}, [id]);
const handleDeliveredBtn = id => {
const newQuantity = parseInt(quantity) - 1;
const updatedQuantity = { newQuantity };
const url = `http://localhost:5000/product/${id}`;
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(updatedQuantity)
})
.then(res => res.json())
.then(data => {
toast('Product delivered successfully.');
})
};
I want to show the updatedQuantity in my UI. Quantity is updated at database. But, without reloading the page, I can’t see any changes that happen in my UI.
2
Answers
You need to use setProduct to cause a render. React components only render whenever there is a change in the state or props, which in your case is invoked by the
setProduct
.You might want to make a shallow copy instead for performance / unnessecary renders but for the sake of example I just added
setProduct(data)
.You need one more
useState
hook to display updated value in your UI. checkout below code:now you can use
updatedQuantity
as a current data in your UI.