简体   繁体   中英

React: Component randomly doesn't refresh after state changes

I am working on a CRUD (express, mongoose, mongodb) which is mostly working as expected... except when it comes to rendering the entries after deleting X amount of them.
Not deleting

Sometimes I can delete 10 entries without any issues, until the component is empty, and other times I delete some entries and then the page just stop rending the updated data and enters an infinite loading state in the browser; only when I hard reload the browser the page renders the latest data, yet it does delete the entry, it just freezes it seems!

From React:
useEffect(() => {
    queryClient.invalidateQueries(["allUsers"]);
  });

const mutation = useMutation({
    mutationFn: async (userid) => {
      return await axios.delete("/api/deleteuser", { data: { userid: userid } });
    },
  });

 const handleDelete = (userid) => {
    mutation.mutate(userid);
    navigate("/", { replace: true });
  };
From Mongoose
const deleteUser = async (req, res) => {
  try {
    await newUser.findOneAndDelete({ userid: req.body.userid });
  } catch (error) {
    return error;
  }
};

Tried invalidating the query cache at the delete function but the result is the same. It just happens randomly, as if the request was not fulfilled... in dev tools.network the request is never fulfilled but the data, whenever it does work, is updated. Network/pending

Edit: I'm using a mongoDB free account... I've read sometimes the response times are not the best, perhaps it is the reason?

  1. useEffect without a dependency array is pretty pointless. It will run every time the component is rerendered.
  2. I assume you are using react-query. Try moving your queryClient.invalidate to onSuccess or onSettled in your useMutation config object. This will ensure your query is invalidated only after the mutation is done. https://react-query-v3.tanstack.com/guides/mutations#mutation-side-effects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM