Documentation
Getting Started
Functions
Guides
Concepts
Client Query
How to fetch on client with SWRTo fetch data using SWR (Stale-While-Revalidate) in Client Components, use the clientQuery
function.
When fetching data using SWR in Client Components, the following sequence occurs:
Step | Environment | Description |
---|---|---|
Pre | Browser | Sends a request to the server for the website at https://example.com . |
Pre | Server | Sends the initial HTML response to the browser. |
1 | Browser | Hydrates the page and initiates a client-side request for data. |
2 | Server | Returns the cached response for the relevant API query. Simultaneously, it begins fetching fresh data from the API to send next. |
3 | Browser | Receives the cached data and displays it immediately. |
4 | Server | Sends the fresh data from the API to the browser while updating the cache for the next requests. |
5 | Browser | Receives the fresh data and updates the UI accordingly. |
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