José Carlos
José Carlos

Reputation: 774

React Query update changes after mutation

i'm being able to update changes in the server side, but it's not updating the client side in real time.

export const updateProfiles = async (payload: Profile[]) => {
  let { error, data } = await supabase.from("profiles").upsert(payload);

  return error ? error : data;
};

export const useProfileMutation = () => {
  const queryClient = useQueryClient();
  return useMutation((payload: Profile[]) => updateProfiles(payload), {
    onSuccess: () => queryClient.invalidateQueries(["profiles", "user"]),
  });
};

I'm getting the data of user and profiles as

export const useProfiles = () => {
  return useQuery(["profiles"], getProfiles);
};

export const useUser = () => {
  return useQuery(["user"], getUser);
};

I have a page that i see some specific user from profiles, when i navigate to that page, i set the user as

  const { data, isLoading } = useProfiles();

  if (isLoading) return <div></div>;

  const profiles = data as Profile[];
  const target = profiles.filter((item) => item.id == id)[0];

If i navigate to home page and then navigate back to that page, the data is up to date, but it's not updating in real time when i change it on the database.

I checked with console.log if the onSuccess is getting triggered and it's working fine. When i call queryClient.invalidadeQueries(["profiles", "user"]), shouldn't it fetch it again and keep the data up to date?

Upvotes: 1

Views: 1954

Answers (1)

OFRBG
OFRBG

Reputation: 1778

queryClient.invalidadeQueries(["profiles", "user"]) invalidates queries with keys matching ["profiles","user", ...]. You want to call it twice as

queryClient.invalidateQueries(["profiles"])
queryClient.invalidateQueries(["user"])

or use the predicate version. Docs: https://tanstack.com/query/v4/docs/guides/query-invalidation

Upvotes: 4

Related Questions