Advise for less boilerplate wanted #1265
RWOverdijk
started this conversation in
General
Replies: 1 comment
-
I came up with this approach: // Made a helper for myself
type ResponseFor<P extends keyof paths> = FetchResponse<"get" extends infer T ? T extends "get" ? T extends keyof paths[P] ? paths[P][T] : unknown : never : never>;
class FetchClient {
private client: ReturnType<typeof createClient<paths>>;
constructor() {
this.client = createClient<paths>({
baseUrl: 'http://localhost:1991/',
});
}
public async get<P extends keyof paths>(path: P, init: FetchOptions<FilterKeys<paths[P], "get">>): Promise<ResponseFor<P>['data']> {
const { data, error } = await this.client.get(path, init);
if (error) throw error;
return data;
}
} Which allows me to export function useAllExamplesQuery() {
return useQuery([RESOURCE_KEY], () => client.get(RESOURCE_KEY, {}));
} It's a lot less boilerplate, but I do have to wrap all of the methods, which I think is fine. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
In my quest to find a decent replacement for GraphQL I am trying to figure out what the boilerplate would be when using this with react query. Right now I have this (where
client
is openapi-fetch):I think this is too much boilerplate. Especially since I'll always want this behaviour (return data, or throw error). It feels like it's something that should be possible to reduce to:
The only thing I can think of is making my own wrapper for either client.get or useQuery. It could maybe be even smaller, but the typings would be a challenge.
Any ideas?
Beta Was this translation helpful? Give feedback.
All reactions