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} />
}