Skip to content

Instantly share code, notes, and snippets.

@tolotrasmile
Created May 2, 2024 03:41
Show Gist options
  • Save tolotrasmile/ae560a8ac57001de65df95755b2ea23d to your computer and use it in GitHub Desktop.
Save tolotrasmile/ae560a8ac57001de65df95755b2ea23d to your computer and use it in GitHub Desktop.
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { type ReactNode } from "react";
interface SuspenseQuery<TData> {
queryOption: UseQueryOptions<T>;
fallback?: ReactNode;
pending?: ReactNode;
children: (data: TData) => ReactNode;
}
export function SuspenseQuery<TData>(props: SuspenseQuery<TData>) {
const { isPending, error, data } = useQuery<TData>(props.queryOption);
if (isPending && props.pending) {
return props.pending;
}
if (!error && data) {
return props.children(data);
}
return props.fallback;
}
@toky-nomena
Copy link

toky-nomena commented May 2, 2024

import type { ReactNode } from "react";
import { useQuery, type QueryOptions } from "react-query";

export interface SuspenseQueryProps<TData> {
  queryOptions: QueryOptions<TData>;
  fallback?: ReactNode;
  loadingElement?: ReactNode;
  errorElement?: (error: unknown) => ReactNode;
  children: (data: TData) => ReactNode;
}

export function SuspenseQuery<TData>({
  children,
  errorElement,
  loadingElement,
  queryOptions,
  fallback,
}: SuspenseQueryProps<TData>) {
  const { isLoading, isError, error, data } = useQuery<TData>(queryOptions);

  if (isLoading) {
    return loadingElement;
  }

  if (isError || !data) {
    return errorElement && error ? errorElement(error) : fallback;
  }

  return children(data);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment