Advanced example ๐Ÿ—ฟ

Last example was good, but here is the best way to use XSWR.

Making our fetcher cancellable โšก๏ธ

Our fetcher was good, but this one can be aborted.

async function fetchAsJson<T>(url: string, more: FetcherMore<T>) {
const { signal } = more
const res = await fetch(url, { signal })
if (!res.ok) {
const error = new Error(await res.text())
return { error }
}
const data = await res.json() as T
return { data }
}

It also returns an error if the request failed.

Defining schemas ๐Ÿ“

Using schemas may seems boilerplate, but it will save you a lot of time later.

function getHelloSchema() {
return getSingleSchema<Hello>("/api/hello", fetchAsJson)
}

It allows you to reuse the same set of key+fetcher+params in multiple places, including imperative code.

Creating mixtures ๐Ÿงช

The mixtures pattern allows you to reuse the same group of blocks.

function useAutoFetchMixture(query: Query) {
useFetch(query)
useVisible(query)
useOnline(query)
}

Mixing it ๐ŸŒช

Once you got a schema and a mixture, you just have to mix it.

function useHelloMix() {
const query = useQuery(getHelloSchema, [])
useAutoFetchMixture(query)
return query
}

Use it in your app ๐Ÿš€

function MyApp() {
const { data, error } = useHelloMix()
if (error)
return <MyError error={error} />
if (!data)
return <MyLoading />
return <MyPage data={data} />
}