Skip to content

How to conditionally preload a query with tanstack? #510

@erickreutz

Description

@erickreutz

Imagine I have a route that accepts an optional query parameter. like /new?id=123 And on this route, we render a form. And given that we have an id we want to pre-load a resource to pre-populate parts of the form. How can I preload a query conditionally based on the presence of a query parameter.

export const Route = createFileRoute("/new")({
  loaderDeps: ({ search: { id } }) => ({ id }),
  loader: async ({ deps, context }) => {
    if (!deps.id) {
      return { queryRef: null };
    }

    // How to skip this?
    const queryRef = context.preloadQuery(MY_QUERY, {
      variables: { id: deps.id },
    });

    return { queryRef };
  },
  component: RouteComponent,
});

function RouteComponent() {
  const { queryRef } = Route.useLoaderData();

  // This breaks when queryRef is null
  const { data } = useReadQuery(queryRef);

  return </>;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions