Tengo que actualizar una cantidad de producto. Actualicé los datos en la base de datos usando la solicitud de colocación, pero en la interfaz de usuario, la página debe volver a cargarse para ver el valor actualizado. Aquí está mi código
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); }) }Debe usar setItem para causar un renderizado. Los componentes de React se vuelven a renderizar automáticamente cada vez que hay un cambio en su estado o accesorios
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); setItem(result) // added setItems }) }Puede crear una función auxiliar fetchData y usarla en useEffect para obtener datos por primera vez y después de colocar datos nuevos.
const ItemDetail = () => { const { itemId } = useParams(); const [item, setItem] = useState({}); const fetchData = () => { const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`; fetch(url) .then(res => res.json()) .then(data => setItem(data)); }, []) } useEffect(() => { fetchData() }, []) const handleDeliverd = () => { const oldQuantity = parseInt(item.quantity) const quantity = oldQuantity - 1; const updatedQuantity = { quantity }; 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) }) .then(fetchData) }