HKS
HKS

Reputation: 1003

Not able to invalidate a query upon successful mutation in React Query

I am developing a MERN stack app & I am using React Query for managing server state.

After I log in, I can create a ticket using a form as shown below:

enter image description here

After filling in the details, when I click on the Create Ticket button, I do two things:

export const usePostTicket = (setTicketError) => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  return useMutation(
    (ticketData) => {
      axios.post("/api/users/tickets/create", ticketData);
    },
    {
      onSuccess: () => {
        navigate("/tickets");
        queryClient.invalidateQueries("tickets");
      },
      onError: ({ message }) => {
        setTicketError(message);
      },
    }
  );
};

However, I don't see any tickets on the page.

enter image description here

This means that the query with the key tickets is not getting refetched in the background.

ONLY when I refocus on the window, I see all the tickets on the page.

enter image description here

QUESTION: Why is the tickets query not getting refetched in the background?

EDIT-1 The following is my custom hook that fetches all the tickets:

export const useGetTickets = () => {
  const response = useQuery(["tickets"], async () => {
    const { data } = await axios.get("/api/users/tickets");
    return data;
  });

  return response;
};

And I am using version 4 of React Query

Upvotes: 0

Views: 3378

Answers (1)

TkDodo
TkDodo

Reputation: 29046

The mutation function doesn't return anything:

(ticketData) => {
  axios.post("/api/users/tickets/create", ticketData);
},

That will make the mutation succeed right away, before the request has finished. Then, the invalidation will run instantly, and it will likely fetch the old data, or you'll have a race condition.

To fix this, return the promise from your mutation function:

(ticketData) => {
  return axios.post("/api/users/tickets/create", ticketData);
},

Upvotes: 6

Related Questions