'state in not getting updated after deleting an id from it until i restart the server

so with my code I'm trying to fill the array 'postuledby' with the id of user who click on the button apply if click on it for the first time the id get sent to the MDB but the button CANCEL is not changing to the button CANCEL until I restart the server also my state is not getting updated immediately i mean that the MDB is getting the id but the state that supposed to to get filled by the id is not updated until the restart of the server . after restarting the server the state get filled with the id and the button change to CANCEL but if i press CANCEL the the id is getting deleted from the MDB and that what i want but the state offer which contain the id is not getting updated that the id was deleted until the restart of the server

here is my code : this is the frontend :

const [user, setUser] = useState({});
  const [offer, setOffer]=useState({});
  const [test, setTest] = useState(false);
  const [apply, setAplly] = useState({ _id: "" });
  const token = localStorage.getItem("token");
  const location = useLocation();
  const { off } = location.state;

  const isLoggedIn = async () => {
    const userLg = await CurrentUser();
    setUser(userLg.data.user);
    setAplly({ ...apply, _id: user._id });
    setOffer(off);
    off.postuledby.filter((el) => {
      if (el._id === user._id) {
        setTest(true);
      }

    });
    
  };

  const hundelUpdate = async () => {
    const config = { headers: { "Content-Type": "application/json" } };
    const res = await axios.put(`/api/offer/apply/${off._id}`, apply, config);
    const result = await axios.get(`/api/offer/getone/${offer._id}`,config);
    setOffer(result.data.ofer)
  };

  const hundelRemove = async () => {
    const config = { headers: { "Content-Type": "application/json" } };
    const res = await axios.put(`/api/offer/deleteapply/${off._id}`, apply, config);
  };

  useEffect(() => {    
    isLoggedIn();   
    
  }, [apply._id,]);
  
  console.log(test);
  console.log(offer);
  console.log(off);

and here is the test on the button :

{token ? (
                <div className="btt">
                  {!off.isAffectted && !test && (
                    <>
                      <Button
                        onClick={hundelUpdate}
                        className="btcl"
                        variant="success"
                      >
                        APLLY
                      </Button>
                    </>
                  )}
                  {off.isAffectted && <p>Sorry Not Available</p>}

                  {test && (
                    <Button
                      onClick={hundelRemove}
                      className="btcl"
                      variant="success"
                    >
                      Cancel
                    </Button>
                  )}
                </div>
              ) : (
                <div className="btt">
                  <Button className="btcl" variant="success" href="/login">
                    Login
                  </Button>
                </div>
              )}

this is the backend :

router.put("/edite/:id", async (req, res) => {
  console.log(req.body);
  try {
    const result = await offerSchema.findByIdAndUpdate(
      { _id: req.params.id },
      { $set: { ...req.body } }
    );
    res.send("offer updated");
  } catch (error) {
    res.status(400).send({ message: "No offer with this id" });
  }
});

router.put("/apply/:id", async (req, res) => {
  console.log(req.body);
  console.log(req.params.id);
  await offerSchema.findOneAndUpdate(
    { _id: req.params.id },
    { $addToSet: { postuledby: req.body } }
  );
});

router.put("/deleteapply/:id", async (req, res) => {
  console.log(req.body._id);
  try {
    offerSchema.findByIdAndUpdate(
      req.params.id,
      { $pull: { postuledby: { _id: req.body._id } } },
      function (err, doc) {
        if (!err) {
          res.status(200).send();
        } else {
          res.render("error", { error: err });
        }
      }
    );
  } catch (error) {
    res.status(400).send({ message: "No offer with this id" });
  }
});
router.put('/getone/:id', async(req,res)=>{
  console.log(req.params.id)
  console.log(ofer)
  const result = await offerSchema.findOne({_id:req.params.id})
  res.status(200).send({ofer : result});
})


Sources

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

Source: Stack Overflow

Solution Source