2

I'm using react query, suppose I have to use some default data. Whenever I have the 'initialData', the queryFn is not being called, hence onSucess is not being called as well. So, the data of that useQuery is still the same of the 'initialData' I have implemented.

   const getProducts = () => {
    console.log("from getProducts");
    //Fetch data
    }

    export const useProducts = () =>
        useQuery({
            queryKey: ["AllProducts"],
            cacheTime: Infinity,
            staleTime: Infinity,
            initialData: {
                products: [],
            },
            queryFn: () => getProducts(),
            onSuccess: (data) => {
                console.log("from onSuccess");
                // Do some stuff
            }

The weird is neither console.log("from getProducts"); nor console.log("from onSuccess"); are being called. I know that I can use 'placeholder' instead of 'initialData'. But the question is why does this happen?

Note that these are the versions of react-query and react-query dev tools:

"@tanstack/react-query": "^4.29.12",
"@tanstack/react-query-devtools": "^4.29.12",

I have used 'placeholder' instead of 'initialData' and it worked.

1 Answer 1

4

That's the desired behaviour of initialData if you combine it with staleTime. initialData is persisted to the cache, and query doesn't care how data goes into the cache - once it's there, staleTime is respected. Since yours is Infinity, the query cache is like: "I have data cached that never gets stale, so I don't need to run the queryFn to revalidate, ever".

If you want a refetch, as you said, placeholderData is your friend. I've written about the differences here: https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query

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.