1

I am trying to pre-fetch data using react-query prefetchQuery. When I am inspecting browser DevTools network tab I can see that data that was requested for prefetchQuery is coming from the back-end but for some reason when I look into react-query DevTools it does generate the key in the cache but for some reason the Data is not there. Let me know what I am doing wrong.

enter image description here enter image description here

import { useState, useEffect } from 'react';
import { useQuery, useQueryClient } from 'react-query';
import axios from 'axios';

const baseURL = process.env.api;

async function getSubCategoryListByCategoryId(id) {
  // await new Promise((resolve) => setTimeout(resolve, 300));
  console.log(`${baseURL}/category/subcategories/${id}`);
  try {
    const { data } = await axios.request({
      baseURL,
      url: `/category/subcategories/${id}`,
      method: 'get',
    });
    console.log('data getSubCategoryListByCategoryId index: ', data);
    return data;
  } catch (error) {
    console.log('getSubCategoryListByCategoryId error:', error);
  }
}

// const initialState = {

// };

const ProductCreate = () => {
  const [values, setValues] = useState(initialState);

  const queryClient = useQueryClient();

  const { data, isLoading, isError, error, isFetching } = useQuery(
    'categoryList',
    getPosts
  );

  const dataList = JSON.parse(data);

  useEffect(() => {
    setValues({ ...values, categories: dataList });

    dataList.map((item) => {
      console.log('useEffect values.categories item.id: ', item._id);
      queryClient.prefetchQuery(
        ['subCategoryListByCategoryId', item._id],
        getSubCategoryListByCategoryId(item._id)
      );
    });
  }, []);

  return <h1>Hello</h1>;
};

export default ProductCreate;

1 Answer 1

3

The second parameter to prefetchQuery expects a function that will fetch the data, similar to the queryFn passed to useQuery.

But here, you are invoking the function, thus passing the result of it into prefetchQuery:

getSubCategoryListByCategoryId(item._id)

if you want to do that, you can manually prime the query via queryClient.setQueryData, which accepts a key and the data for that key passed to it.

otherwise, the fix is probably just:

() => getSubCategoryListByCategoryId(item._id)
Sign up to request clarification or add additional context in comments.

Comments

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.