Search

clientQuery

How to use clientQuery in your project

clientQuery is a client-side function that fetches data from a URL. The function accepts queryUrl, queryOptions and queryCache as parameters, and returns with data, error, and loading properties.

Fetching Strategies

clientQuery supports three different fetching strategies:

  • "fresh" — fetches fresh data
  • "cached" — fetches cached data
  • "swr" — fetches cached + fresh data

API Reference

Use clientQuery in a client component using the following format:

"use client";
import { clientQuery } from "@bigbang-sdk/next-query";

function ClientComponent() {
    const { data, error, isLoading } = clientQuery({
        // required
        queryUrl: "https://api.example.com/data",
        // optional, defaults to "GET"
        queryOptions: {
          method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ foo: "bar" }),
        },
        // optional, defaults to false
        queryCache: true,
        // or queryCache: false,
        // or queryCache: "swr",
        // or queryCache: { tags: ["user","profile"], revalidate: 60 },
    });

    console.log(data, error, isLoading);
}

Parameters

clientQuery accepts the following parameters:

type ClientQueryProps = {
  queryUrl: string;
  queryOptions: RequestInit;
  queryCache: boolean | CacheProps;
};
ParameterTypeDescription
queryUrlstringThe URL to fetch.
queryOptionsRequestInitThe options for the fetch request.
queryCacheboolean / "swr" / cachePropsThe cache options for the fetch request.

queryOptions

queryOptions is an object that contains the options for the fetch request.

type QueryOptions = {
  method: string;
  headers: Record<string, string>;
  body: string;
};
ParameterTypeDescription
methodstringThe HTTP method to use.
headersRecordThe headers to send with the request.
bodystringThe body to send with the request.

queryCache

queryCache is used to specify the cache options for the fetch request.

type QueryCache =
  | boolean
  | "swr"
  | {
      tags: string[];
      revalidate: number;
    };

It can be a boolean, the string "swr" or an object with the following properties:

ParameterTypeDescription
tagsstring[]The tags to use for the cache.
revalidatenumberThe number of seconds before the cache is considered stale.

Return Values

type ClientQueryReturn = {
  data: any;
  error: Error | null;
  isCacheLoading: boolean;
  isFreshLoading: boolean;
  isLoading: boolean;
};
ParameterTypeDescription
dataanyThe data returned from the fetch.
errorError / nullThe error returned from the fetch.
isCacheLoadingbooleanapplicable only in "swr" mode. true until the first (cached) data arrives.
isFreshLoadingbooleanapplicable only in "swr" mode. true until the second (fresh) data arrives.
isLoadingbooleanin "swr" mode, true until both cached and fresh data have arrived. Otherwise, true until the data arrives.

Made with

by Bigbang