Bardhok Ajvazi
Bardhok Ajvazi

Reputation: 13

useMutation with @tanstack/react-query doesn't refresh component

When i use useMutate from tanstack/react-query, my useQuery doesn't get updated.

const {
    isLoading,
    error: queryError,
    data: queryData,
  } = useQuery({
    queryKey: ["data"],
    queryFn: async () => {
      try {
        const dataRes = await axios.get("http://localhost:3000/Interface");
        console.log(dataRes);
        return dataRes.data;
      } catch (error) {
        console.error(error);
        return null;
      }
    },
  });

  const { isPending, mutate, error, data } = useMutation({
    mutationKey: ["data"],
    mutationFn: async () => {
        const response = await axios.post(
          "http://localhost:3000/Interface",
          postData,
          { headers },
        );
        return response.data;
    },
    onSuccess: () => {
      console.log('onSuccess');
      return   queryClient.invalidateQueries(['data']);
    }
  });

Even if i try to return invalidateQueries with onSuccess, it doesn't work. I've checked others post but it didn't resolve my issue. Somehow, if i change tab in the browser, it got updated.

Thank you in advance for any answer.

I tried to return invalidateQueries with onSuccess on useMutation.

Upvotes: 1

Views: 3143

Answers (3)

KHAWAR SHEHZAD
KHAWAR SHEHZAD

Reputation: 11

export const useContactListQuery = (page = 1, search = '') => {
  const auth = useAuth();
  return useQuery({
    queryKey: ["contacts", page, search],
    queryFn: async () => {

      const response = await api.get("/api/common/contacts/", {
        params: {
          page: page,
          pageSize: 10,
          search: search,
        },
        headers: { 'Authorization': `Bearer ${auth.token}` }
      });
      return response.data;
    },
  });
};

Step1: first Import this hook:

import { useContactListQuery } from "../../hooks/GetRequest";

Step 2: Declaring the Hook Look Like this.

  const { data, isLoading, isError, error } = useContactListQuery(page, search);

Step 3:

const contacts = data?.results || [];
const totalRecords = data?.pagination?.total || 0;
const pageSize = data?.pagination?.pageSize || 10;

Step 4:

{contacts.map((data, index) => (  ....
)}

Upvotes: 1

Nay
Nay

Reputation: 727

Or you can try:

onSuccess: () => {
     queryClient.refetchQueries({ queryKey: ['data'] })
  }

Upvotes: 0

Adam Jenkins
Adam Jenkins

Reputation: 55643

Just so you know, mutationKey has no relation to queryKey - doesn't matter if they're the same, they have nothing to do with each other.

invalidateQueries is the correct thing to do, but it looks like you're using the wrong parameter, it should be an object with a property of queryKey instead of the queryKey itself.

queryClient.invalidateQueries({queryKey: ['data']});

See the docs

Upvotes: 1

Related Questions