Search

serverQuery

How to use serverQuery in your project

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

Fetching Strategies

serverQuery supports two different fetching strategies:

  • "fresh" — fetches fresh data
  • "cached" — fetches cached data

API Reference

Use serverQuery in a server component using the following format:

import { serverQuery } from "@bigbang-sdk/next-query";

async function ServerComponent() {
  const { data, error } = await serverQuery({
        // 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: { tags: ["user","profile"], revalidate: 60 },
      });

  console.log(data, error);
}

Parameters

serverQuery accepts the following parameters:

type ServerQueryProps = {
  queryUrl: string;
  queryOptions: RequestInit;
  queryCache: boolean | CacheProps;
};
ParameterTypeDescription
queryUrlstringThe URL to fetch.
queryOptionsRequestInitThe options for the fetch request.
queryCacheboolean / 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
  | {
      tags: string[];
      revalidate: number;
    };

It can be a boolean 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 ServerQueryReturn = {
  data: any;
  error: Error | null;
};
ParameterTypeDescription
dataanyThe data returned from the fetch.
errorError / nullThe error returned from the fetch.

Made with

by Bigbang