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
[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:
function useUser({ params, body, reactQuery }:UseQueryOptions<paths[typeofGET_USER]["get"]>) {
137
+
returnuseQuery({
138
+
...reactQuery,
139
+
queryKey: [
140
+
GET_USER,
141
+
params.path.user_id,
142
+
// add any other hook dependencies here
143
+
],
144
+
queryFn: () =>
145
+
client
146
+
.get(GET_USER, {
147
+
params,
148
+
// body - isn’t used for GET, but needed for other request types
149
+
})
150
+
.then((res) => {
151
+
if (res.data) returnres.data;
152
+
thrownewError(res.error.message); // React Query expects errors to be thrown to show a message
153
+
}),
154
+
});
155
+
}
98
156
99
-
### Custom cache wrapper
157
+
/**
158
+
* MyComponent example usage
159
+
*/
100
160
101
-
> ⚠️ You probably shouldn’t use this, relying instead on [built-in Fetch caching behavior](#built-in-fetch-caching)
161
+
interfaceMyComponentProps {
162
+
user_id:string;
163
+
}
102
164
103
-
Say for some special reason you needed to add custom caching behavior on top of openapi-fetch. Here is an example of how to do that using <ahref="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"target="_blank"rel="noopener noreferrer">proxies</a> in conjunction with the <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control"target="_blank"rel="noopener noreferrer">Cache-Control</a> header (the latter is only for the purpose of example, and should be replaced with your caching strategy).
165
+
function MyComponent({ user_id }:MyComponentProps) {
-`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?).
175
+
- Saving the pathname as `GET_USER` is an important concept. That lets us use the same value to:
176
+
1. Query the API
177
+
2. Infer types from the OpenAPI schema’s [Paths Object](https://spec.openapis.org/oas/latest.html#paths-object)
178
+
3. Cache in React Query (using the pathname as a cache key)
179
+
- Note that `useUser()` types its parameters as `UseQueryOptions<paths[typeof GET_USER]["get"]>`. The type `paths[typeof GET_USER]["get"]`:
180
+
1. Starts from the OpenAPI `paths` object,
181
+
2. finds the `GET_USER` pathname,
182
+
3. and finds the `"get"` request off that path (remember every pathname can have multiple methods)
183
+
- To create another hook, you’d replace `typeof GET_USER` with another URL, and `"get"` with the method you’re using.
184
+
- 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.
115
185
116
-
function parseMaxAge(cc:string|null):number {
117
-
// if no Cache-Control header, or if "no-store" or "no-cache" present, skip cache
// update cache on success and response is cacheable
140
-
elseif (result.data) {
141
-
resultCache.set(url, result);
142
-
if (nextExpiry) expiryCache.set(url, nextExpiry);
143
-
}
144
-
returnresult;
145
-
}
146
-
147
-
// otherwise, serve cache
148
-
returnresultCache.get(url);
149
-
},
150
-
});
188
+
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