A custom data composable
Goal: a useFetch of your own that always talks to one API, with its base URL and headers set once. In Nuxt this is useFetch wrapped in a composable, or createUseFetch.
- Make the function with
createUseFetch(defaults)from your adapter.defaultsis an options object, or a function that gets the call's options and returns the ones to use. It is the same name in all six adapters.
import { createUseFetch } from "@hamur/adapter-react"
export const useApi = createUseFetch({ baseURL: "/api", headers: { "x-client": "web" }, lazy: true })
- Use it as
useFetch. A call's own option wins over a default,headersmerge by name andqueryby key, and the key of the entry is still made from the URL, so the server render and the browser share one fetch:
import { useApi } from "./use-api.ts"
export default function Todos() {
const todos = useApi<{ id: number; title: string }[]>("/todos")
if (todos.status === "pending") return <p>Loading</p>
return (
<ul>
{todos.data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
For a call to a handler of your own app, prefer useAsyncData(handler, input): the types come from the handler. createUseAsyncData(defaults) does for useAsyncData what this does for useFetch. A function made by createUseFetch does not check body and query against your routes, because the defaults may change what a call sends.
See also: Data, Adapters reference.