Your first mix ๐งช
When using xswr and its composition-based hooks, you create a mix and only include the ingredients you want.
We'll do a request at /api/data
using JSON, display it with a loading, and automatically refetch it.
Create a fetcher โก๏ธ
It will just take an url, fetch it, and return the data.
async function fetchAsJson<T>(url: string) { const res = await fetch(url) const data = await res.json() as T return { data }}
Create a mix ๐ช
Then create a mix using a query and some blocks.
function useHello() { const query = useSingleQuery<Hello>(`/api/hello`, fetchAsJson) useFetch(query) // Fetch on mount and on url change useVisible(query) // Fetch when the page becomes visible useOnline(query) // Fetch when the browser becomes online return query}
Use it in your components ๐
function MyApp() { const { data, error } = useHello() if (error) return <MyError error={error} /> if (!data) return <MyLoading /> return <MyPage data={data} />}