I have to update a quantity of product. I have update the data in database using put request but in UI the page need to reload to see the updated value. Here is my code
const ItemDetail = () => {
const { itemId } = useParams();
const [item, setItem] = useState({});
useEffect(() => {
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url)
.then(res => res.json())
.then(data => setItem(data));
}, [])
//handle qantity deliver item
const handleDeliverd = () => {
const oldQuantity = parseInt(item.quantity)
const quantity = oldQuantity - 1;
const updatedQuantity = { quantity };
//send data to server
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(updatedQuantity)
})
.then(res => res.json())
.then(result => {
console.log(result);
})
}
2
Answers
You need to use
setItem
to cause a render. React components automatically re-render whenever there is a change in their state or propsYou can create an auxiliary function fetchData and use it in useEffect to fetch data first time and after putting new data.