Trying to build a simple CRUD proof of concept app with GoHighLevel v.1 API at the backend. during Insert and Delete it is updating the screen but one step behind. I mean, when Item1 is deleted it deletes the item from the backend but does nothing on screen. But when Item2 is deleted, Item1 disappears from the screen and Item2 is deleted from the backend. Same with insert. I'm dropping my hooks code here which are being used in this project:
GET ALL HOOK
import { useQuery } from "@tanstack/react-query";
import ms from "ms";
import { ApiResponse } from "../services/apiClient";
import contactService from "../services/contactService";
import { CACHE_KEY_CONTACTS, Contact } from "../entities";
const useContacts = () =>
useQuery<ApiResponse<Contact>, Error>({
queryKey: [CACHE_KEY_CONTACTS, "all"],
queryFn: contactService.getAll,
staleTime: ms("2m"), // 2 minutes
});
export default useContacts;
INSERT HOOK
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { CACHE_KEY_CONTACTS, Contact } from "../entities";
import contactService from "../services/contactService";
const useAddContact = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (newContact: Contact) => {
console.log("Adding contact", newContact);
return contactService.post(newContact);
},
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries([CACHE_KEY_CONTACTS, "all"]);
// queryClient.refetchQueries(CACHE_KEY_CONTACTS);
},
// onSettled: () => {
// // Force a refetch of the contacts after mutation is settled
// queryClient.refetchQueries(CACHE_KEY_CONTACTS);
// },
});
};
export default useAddContact;
As you can see I've used queryClient.refetchQueries
and onSettled:
block just as extra effort to make it work. But that didn't work so I commented it out.
DELETE HOOK
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { CACHE_KEY_CONTACTS } from "../entities";
import contactService from "../services/contactService";
const useDeleteContact = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => {
return contactService.delete(id);
},
onSuccess: () => {
queryClient.invalidateQueries([CACHE_KEY_CONTACTS, "all"]);
queryClient.refetchQueries([CACHE_KEY_CONTACTS, "all"]);
},
});
};
export default useDeleteContact;
Now, the interesting fact is that I've used this exact same code with a local JSON Server and that works perfectly. This tells me the problem might be the backend or some sort of delay at the backend. Can anyone please confirm? Can anyone please tell me what I'm doing wrong here?
And, yes, I know that I probably have to use an optimistic update in this case. Which I have been trying without luck. Which also works fine with a local JSON server but doesn't work with GoHighLevel API. Any help in the right direction will be highly appreciated. In case, I have to drop React Query and choose something like Context/Reducer model, RTK or Zustand please let me know.