'How to update value in client site using mongodb?

I am using React in front-end and Node and MongoDB in Back-end. I have created a custom hook from where I am loading the data. The following is the custom hook

import { useEffect, useState } from "react";

const useItems = (id) => {
  const [item, setItem] = useState([]);

  useEffect(() => {
    fetch(`http://localhost:5000/inventory/${id}`)
      .then((res) => res.json())
      .then((data) => setItem(data));
  }, [id]);

  return [item];
};

export default useItems;

And this is the component where I am calling the custom hook to load the data.

import React, { useEffect, useState } from "react";
import "./Inventory.css";
import { useParams } from "react-router-dom";
import useItems from "../../hooks/useItems";

const Inventory = () => {
  const { id } = useParams();
  const [item] = useItems(id);

  const quantityDecrease = (newQuantity) => {
    let quantity = parseInt(newQuantity) - 1;
    const updateQuantity = { quantity };
    const url = `http://localhost:5000/inventory/${id}`;

    fetch(url, {
      method: "PUT",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(updateQuantity),
    })
      .then((res) => res.json())
      .then((data) => {
        console.log("success", data);
        alert("saved");
      });
  };

  return (
    <div>
              <div className="col-lg-6">
                <p className="inventory-textbox">
                  <strong>Quantity :</strong> {item.quantity}
                </p>
              </div>
                <button onClick={() => quantityDecrease(item.quantity)}>
                   Delivered
                </button>
          </div>
  );
};

export default Inventory;

Whenever the Delivered button is clicked the quantityDecrease function is executed and the quantity of the item is decreased by one. Now, my database is working fine. I am being able to update both client and server site but I have to reload the page in order to see the change in the ui. Is there a way I do not have to reload to see the change?



Solution 1:[1]

try using the item data as useEffect dependency. it may solve your problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehedi Hasan