0

React query doesn't sustain its cache after queryClient.setQueryData, also it's not working on defaultOptions like under. i am using react query developer tool and it show that that data get stored after API call but i saw a property gcTimeout: 23. i think this is effecting and have tried every possible solution available on internet.

// defined in app.tsx


const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: Infinity,
      cacheTime: 100000, // 10 min
    },
  },
});


<QueryClientProvider client={queryClient}>


let me share the custom hook i created for mutation. and how i am calling it.

// defined in hooks/useFetch.ts


const useFetch = (requests: Request[]) => {
  const queryClient = useQueryClient();

  const fetchDataAndMutate = () => {
    return requests.map((request) => {
      const {
        key,
        api, 
        save = true,
      } = request;

      
      const {mutate, isLoading} = useMutation({
        mutationFn: async (payload) => postUtil(api, payload),
        onMutate: (variables) => {
          return {id: 1};
        },
        onError: (error, variables, context) => {
          // An error happened!
          console.log(`Error: ${error}`);
        },
        onSuccess: (response, variables, context) => {
          if (response.status) {
            if (response.status === 200) {
              //success
              if (save) queryClient.setQueryData([key], response.data.data);
            }
          } else if (response.response.status) {
            console.log(
              "response.response.status",
              response.response.data.Message
            );
          }
        },
      });
      return {
        mutate,
        isLoading,
      };
    });
  };
  const mutates = fetchDataAndMutate();

  useEffect(() => {
    // to hit api as it is defined
    requests.forEach((request, index) => {
      if (request?.init)
        if (typeof mutates[index].mutate === "function")
          mutates[index].mutate();
    });
  }, []);

  return mutates;
};


used the hooks as following ->

// defined in containers/analysis

const apiConfig = [
  {
    key: ALL_MAPPING_AREAS,
    api: getAllMappingAreasApi, 
    init: true,
  },
  {
    key: MAPPING_AREA_DETAIL,
    api: getMappingAreaDetailApi, 
  },
];

const mutates = useFetch(apiConfig);
const [
  getAllMappingAreas,
  getBoundedAreaDetail,
] = mutates;


const allMappingAreas = queryClient.getQueryData([ALL_MAPPING_AREAS]);
const mappingAreaDetail = queryClient.getQueryData([MAPPING_AREA_DETAIL]);

// i am receiving data in allMappingAreas but it vanish fater almost 5min

1 Answer 1

1

You are not creating an Observer because you are not using the useQuery hook, so the Query counts as "unused" and is garbage collected after the default of 5 minutes.

You can just tweak cacheTime to be a different value, however, it's not a good idea to retrieve data with queryClient.getQueryData - you really want to use useQuery to get a reactive hook that will automatically re-render your component when updates come in for that Query. Using mutations instead (for GET requests in general) is not a good idea because mutations don't share or deduplicate state like queries do.

Sign up to request clarification or add additional context in comments.

3 Comments

i really appreciate the time you get to answer. the reason for not using useQuery was that I had to use POST method and I am getting data through POST api after passing it some payload. i cannot change api as it is being designed and fnalized so i need to manage it on client side.
now i have changed it exactly where the problem is. it would be easy to understand.
what about the use case where queryData is needed by functions outside of components?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.