You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
openapi-fetch doesn’t provide any caching utilities. But this library is so lightweight, caching can be added easily.
73
+
openapi-fetch is simple vanilla JS that can be used in any project. But sometimes the implementation in a framework may come with some prior art that helps you get the most out of your usage.
74
74
75
-
### Built-in Fetch caching
75
+
### React + React Query
76
76
77
-
Out-of-the box, most browsers do a darn good job of caching Fetch requests, especially when caching is configured properly on the API end (the appropriate <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control"target="_blank">Cache-Control</a> headers are served):
77
+
[React Query](https://tanstack.com/query/latest) is a perfect wrapper for openapi-fetch in React. At only 13 kB, it provides clientside caching and request deduping across async React components without too much client weight in return. And its type inference preserves openapi-fetch types perfectly with minimal setup.
78
78
79
-
```ts
80
-
// src/lib/api/index.ts
81
-
importcreateClientfrom"openapi-fetch";
82
-
import { paths } from"./v1";
83
-
84
-
exportdefaultcreateClient({
85
-
baseUrl: "https://myapi.dev/v1",
86
-
cache: "default", // (recommended)
87
-
});
88
-
89
-
// src/some-other-file.ts
90
-
importclientfrom"./lib/api";
91
-
92
-
client.GET("/my/endpoint", {
93
-
/* … */
94
-
});
95
-
```
96
-
97
-
Beyond this, you’re better off using a prebuilt fetch wrapper in whatever JS library you’re consuming:
98
-
99
-
-**React**: [React Query](#react-query)
100
-
-**Svelte**: (suggestions welcome — please file an issue!)
101
-
-**Vue**: (suggestions welcome — please file an issue!)
For idempotent data fetching (not having to wrestle with promises—great for UI applications), [Nano Stores](https://github.com/nanostores/nanostores) is a great pair with `openapi-fetch`. This general strategy could also be used in simple UI applications or Web Components:
Keep in mind, though, that reactivity is difficult! You’ll have to account for stale data in the context of your application (if using a JS framework, there are already existing libraries that can handle this for you). Further, this is a contrived example that doesn’t handle invalidating the cache—both data and errors. Cache invalidation will be dependent on your specific needs.
165
-
166
-
If you need to work with promises, then just using `openapi-fetch` as-is will usually suffice. If you need promises + caching, then you’ll have to come up with a solution that fits your own custom usecase.
167
-
168
-
## React Query
169
-
170
-
[React Query](https://tanstack.com/query/latest) is a perfect wrapper for openapi-fetch in React. At only 13 kB, it provides clientside caching and request deduping across async React components without too much client weight in return. And its type inference preserves openapi-fetch types perfectly with minimal setup. Here’s one example of how you could create your own [React Hook](https://react.dev/learn/reusing-logic-with-custom-hooks) to reuse and cache the same request across multiple components:
-`UseQueryOptions<T>` is a bit technical, but it’s what passes through the `params` and `body` options to React Query for the endpoint used. It’s how in `<MyComponent />` you can provide `params.path.user_id` despite us not having manually typed that anywhere (after all, it’s in the OpenAPI schema—why would we need to type it again if we don’t have to?).
234
-
- Saving the pathname as `GET_USER` is an important concept. That lets us use the same value to:
235
-
1. Query the API
236
-
2. Infer types from the OpenAPI schema’s [Paths Object](https://spec.openapis.org/oas/latest.html#paths-object)
237
-
3. Cache in React Query (using the pathname as a cache key)
238
-
- Note that `useUser()` types its parameters as `UseQueryOptions<paths[typeof GET_USER]["get"]>`. The type `paths[typeof GET_USER]["get"]`:
239
-
1. Starts from the OpenAPI `paths` object,
240
-
2. finds the `GET_USER` pathname,
241
-
3. and finds the `"get"` request off that path (remember every pathname can have multiple methods)
242
-
- To create another hook, you’d replace `typeof GET_USER` with another URL, and `"get"` with the method you’re using.
243
-
- Lastly, `queryKey` in React Query is what creates the cache key for that request (same as hook dependencies). In our example, we want to key off of two things—the pathname and the `params.path.user_id` param. This, sadly, does require some manual typing, but it’s so you can have granular control over when refetches happen (or don’t) for this request.
244
-
245
-
### Further optimization
246
-
247
-
Setting the default [network mode](https://tanstack.com/query/latest/docs/react/guides/network-mode) and [window focus refreshing](https://tanstack.com/query/latest/docs/react/guides/window-focus-refetching) options could be useful if you find React Query making too many requests:
0 commit comments