Memoizing fetch error: Body is unusable
MangoMarcus opened this issue · comments
Marcus commented
Description
I've tried to memoize the fetch function for graphql-request using lodash.memoize, but it gives "Error: Body is unusable". Is this a bug or am I missing something?
Thanks
Reproduction Steps/Repo Link
import { GraphQLClient } from 'graphql-request';
import memoize from 'lodash/memoize';
export const gqlClient = new GraphQLClient(GRAPHQL_URL, {
fetch: memoize(
fetch,
(...args) => JSON.stringify(args)
),
});
Screenshot
For reference the gqlSdk
in the screenshot is generated by graphql-codegen using import { getSdk, type SdkFunctionWrapper } from '@/generated/gql/sdk'; export const gqlSdk = getSdk(gqlClient);
, it's just a simple wrapper around gqlClient.request
though so the effect should be the same:
Workaround
I've worked around the issue for now by memoizing the individual methods in that sdk instead of the underlying fetch
const unmemoizedGqlSdk = getSdk(gqlClient);
export const gqlSdk = Object.fromEntries(
Object.entries(unmemoizedGqlSdk).map(([key, value]) => [
key,
memoize(value, (...args) => JSON.stringify(args)),
]),
);