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.
import { getSchema } from '@hazae41/xswr';
function getHelloSchema() {
return getSchema<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.
import { useFetch, useVisible, useOnline } from '@hazae41/xswr';
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.
import { useSchema, useAutoFetchMixture } from '@hazae41/xswr';
function useHelloMix() {
const query = useSchema(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} />
}