Reputation: 1003
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:
After filling in the details, when I click on the Create Ticket
button, I do two things:
tickets
(queryClient.invalidateQueries("tickets")
), so that the "/tickets" route has the latest list of tickets. My understanding here is that invalidating a query will make the query refetch in the background.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);
},
}
);
};
tickets
page (navigate("/tickets")
). This is the page where I should be able to see all my tickets, including the newly created ticket.However, I don't see any tickets on the page.
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.
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
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