Search

Client Query

How to fetch on client with SWR

To fetch data using SWR (Stale-While-Revalidate) in Client Components, use the clientQuery function.

Query Pattern

When fetching data using SWR in Client Components, the following sequence occurs:

SWRFetched from the server, while revalidatingAPISingaporeServerSan FranciscoBrowserSan Francisco
StepEnvironmentDescription
PreBrowserSends a request to the server for the website at https://example.com.
PreServerSends the initial HTML response to the browser.
1BrowserHydrates the page and initiates a client-side request for data.
2ServerReturns the cached response for the relevant API query. Simultaneously, it begins fetching fresh data from the API to send next.
3BrowserReceives the cached data and displays it immediately.
4ServerSends the fresh data from the API to the browser while updating the cache for the next requests.
5BrowserReceives the fresh data and updates the UI accordingly.

GET Request

The following example fetches data on the client using a GET request. The data is initially set with the cached response, and then automatically updated with the fresh data once it's fetched.

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

function ClientComponent() {
    const { data, error, isLoading, isCacheLoading, isFreshLoading } = clientQuery({
        queryUrl: "https://api.example.com/data",
        queryCache: "swr"
    });

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

Made with

by Bigbang