Replies: 1 comment 1 reply
-
|
Been using SWR in production across several apps with 50k+ daily users. Here are patterns that held up well. Fetcher FunctionDefine a base fetcher for GET requests and create specialized ones when you need different HTTP methods or headers: const fetcher = async <T>(url: string): Promise<T> => {
const res = await fetch(url, {
headers: { Authorization: `Bearer ${getToken()}` },
});
if (!res.ok) throw new FetchError(res.status, await res.text());
return res.json();
};
// Provide globally
<SWRConfig value={{ fetcher }}>{children}</SWRConfig>For mutations, For abort support, the fetcher receives an const fetcher = (url: string, { signal }: { signal: AbortSignal }) =>
fetch(url, { signal }).then((r) => r.json());Parameterized Queries (Filters, Pagination)Encode parameters in the SWR key. The cache key IS the query: function useFilteredData(filters: Filters, page: number) {
const params = new URLSearchParams({ ...filters, page: String(page), limit: "20" });
return useSWR<SearchResult>(`/api/items?${params}`);
}Do NOT use Other Lessons
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm imagining something similar to what Theo did with Stripe Theo's recommendations, only let's get advice from as many people as possible. Here are three things I would love to know how others handle:
The fetcher function
Handling a SELECT statement that has many parameters
In a few places in my app, I need to collect information from the user (such as filters, pagination, and an input field), which gets used to create an SQL query on the backend. Is it better in this situation to pass all that information as query parameters or use the trigger function returned by the useSWRMutation hook?
Beta Was this translation helpful? Give feedback.
All reactions