TanStackT
TanStack3y ago
3 replies
faint-white

createInfiniteQuery runs fetch, when initialData is defined

Hello, I have a main page in SvelteKit that has the following structure:
+page.svelte
  import {createInfiniteQuery} from '@tanstack/svelte-query';
  export let data; // this has the initial data
  
  const getPublishedRecipes = async ({ pageParam = 0 }) => {
    const response = await fetch("http://localhost:5016/api/snippets/published?cursor=" + pageParam, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    });
    return await response.json();
  };

  const query = createInfiniteQuery({
    queryKey: ['data'],
    queryFn: getPublishedRecipes,
    initialData: data,
    //@ts-ignore
    getNextPageParam: (lastPage) => {
      if (lastPage.next) {
        const nextUrl = new URLSearchParams(new URL(lastPage.next).search)
        const nextCursor = nextUrl.get('page')
        if (nextCursor) {
          return +nextCursor
        }
      }
      return undefined
    },
  })
  const { error } = $query


And in the +page.server.js:

import { error } from '@sveltejs/kit';

const getPublishedRecipes = async ({pageParam = 0}) => {
  const response = await fetch('http://localhost:5016/api/snippets/published?cursor=' + pageParam, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }
  });
  return await response.json();
};

/** @type {import('./$types').PageLoad} */
export async function load() {
  // Check if slug params exist
  return await getPublishedRecipes({pageParam: 0}).then(x => {
    return x;
  }).catch(() => {
    throw error(404, 'Not found');
  })
}


I have defined the initial data as the actual
data
that it's retrieved on the Page Load, that corresponds to the first set of articles or recipes.

Given the initial data is set in the createInfiniteQuery, Is there any reason for this or workaround so that it doesn't try to fetch again the data that was fetched from the server?
image.png
Was this page helpful?