Skip to content

useLazyQuery cannot be prefetched on the server #1495

@Csszabi98

Description

@Csszabi98

Describe the bug
As of now, useLazyQuery cannot be prefetched during ssr, as the "forceDisabled" value passed to the underlying implementation is always set to "true".

Expected behavior
useLazyQuery should accept a new parameter allowing consumers to decide if the query should be disabled out of the box.

Workaround
Call useQuery or useLazyQuery conditionally based on if the query should or should not be eager:

import { UseQueryOptions, useLazyQuery, useQuery } from '@vue/apollo-composable';
import type {
  DocumentParameter,
  OptionsParameter,
  UseQueryReturn,
  VariablesParameter,
} from '@vue/apollo-composable/dist/useQuery.js';
import { DocumentNode } from 'graphql';

type UseLazyQueryReturn<TResult, TVariables extends Record<string, unknown>> = UseQueryReturn<
  TResult,
  TVariables
> & {
  load: (
    document?: DocumentNode | null,
    variables?: TVariables | null,
    options?: UseQueryOptions | null,
  ) => boolean;
};

export function useLazyQuerySsrSafe<
  TResult = unknown,
  TVariables extends Record<string, unknown> = Record<string, unknown>,
>(
  document: DocumentParameter<TResult, TVariables>,
  variables?: VariablesParameter<TVariables>,
  options?: OptionsParameter<TResult, TVariables>,
  eager = false, // This line does the trick, enables prefetching for lazy queries
): UseLazyQueryReturn<TResult, TVariables> {
  if (eager) {
    const query = useQuery(
      document,
      variables as VariablesParameter<TVariables>,
      options as OptionsParameter<TResult, TVariables>,
    );

    return {
      ...query,
      // set to have a compatible api
      load() {
        return query.forceDisabled.value;
      },
    };
  }

  return useLazyQuery(document, variables, options);
}

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