TanStackT
TanStack12mo ago
43 replies
skinny-azure

Cache seemingly not working

I'm trying to use tanstack query to call my AWS AppSync GraphQL API, which is working in that it sends a request and receives a response, however it doesn't appear to be caching the response from the API (when I use the refetch function, it always resends a network request to the API.

Here's some minimal code:
const getActiveProgrammes = async () => {
    console.log("getActiveProgrammes...");
    const apiClient = getApiClient();

    const resp = await apiClient.graphql({ query: getActiveProgrammesQuery });
    if (resp.errors !== undefined && resp.errors.length > 0) {
        console.log(JSON.stringify({ errors: resp.errors }));
        throw new Error(resp.errors.map((error) => error.toJSON()).join("\n"));
    }
    console.log(
        `getActiveProgrammes done: ${JSON.stringify(
            resp.data.getActiveProgrammes
        )}`
    );
    return resp.data.getActiveProgrammes;
};

const Programmes = () => {
    const { data, error, isPending, refetch } = useQuery({
        queryFn: getActiveProgrammes,
        queryKey: ["activeProgrammes"],
        staleTime: 1000 * 30 // should cache for 30 seconds
    });


    if (isPending) return "Fetching data from backend...";
    if (error) return `An error occurred getting data: ${error.message}`;
    return <>
        <div>
            {data.length === 0 ? (
                <p>No programmes</p>
            ) : (
                data.map((programme) => (
                    ...
                ))
            )}
        </div>
        <button onClick=() => void refetch()}>Refresh Data</button>
    </>
}

const queryClient = new QueryClient();

ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
        <QueryClientProvider client={queryClient}>
            <Programmes />
        </QueryClientProvider>
    </React.StrictMode>
);
Any ideas as to why it's not caching?
Was this page helpful?