swr#Fetcher TypeScript Examples

The following examples show how to use swr#Fetcher. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: query-data.tsx    From plasmic with MIT License 6 votes vote down vote up
/**
 * Fetches data asynchronously using SWR Hook (https://swr.vercel.app/)
 *
 * @param key a unique key for this data fetch; if data already exists under this
 *   key, that data is returned immediately.
 * @param fetcher an async function that resolves to the fetched data.
 * @param options (optional) an object of options for this hook (https://swr.vercel.app/docs/options).
 * @returns an object with either a "data" key with the fetched data if the fetch
 *   was successful, or an "error" key with the thrown Error if the fetch failed.
 */
export function useMutablePlasmicQueryData<T, E>(
  key: Key,
  fetcher: Fetcher<T>,
  options?: SWRConfiguration<T, E>
) {
  const prepassCtx = React.useContext(PrepassContext);

  const opts: SWRConfiguration = prepassCtx ? { suspense: true } : {};

  const config = useSWRConfig();
  React.useEffect(() => {
    __SWRConfig = config;
  }, [config]);

  return useSWR(key, fetcher, { ...options, ...opts });
}
Example #2
Source File: query-data.tsx    From plasmic with MIT License 5 votes vote down vote up
/**
 * Fetches data asynchronously. This data should be considered immutable for the
 * session -- there is no way to invalidate or re-fetch this data.
 *
 * @param key a unique key for this data fetch; if data already exists under this
 *   key, that data is returned immediately.
 * @param fetcher an async function that resolves to the fetched data.
 * @returns an object with either a "data" key with the fetched data if the fetch
 *   was successful, or an "error" key with the thrown Error if the fetch failed.
 */
export function usePlasmicQueryData<T>(
  key: Key,
  fetcher: Fetcher<T>
): { data?: T; error?: Error; isLoading?: boolean } {
  const prepassCtx = React.useContext(PrepassContext);

  // @plasmicapp/query is optimized for SSR, so we do not revalidate
  // automatically upon hydration; as if the data is immutable.
  const opts: SWRConfiguration = {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
  };
  if (prepassCtx) {
    // If we're doing prepass, then we are always in suspense mode, because
    // react-ssr-prepass only works with suspense-throwing data fetching.
    opts.suspense = true;
  }

  const config = useSWRConfig();
  React.useEffect(() => {
    __SWRConfig = config;
  }, [config]);

  const resp = useSWR(key, fetcher, opts);
  if (resp.data) {
    return { data: resp.data };
  } else if (resp.error) {
    return { error: resp.error };
  } else {
    return { isLoading: true };
  }
}