React.cache() with object as parameter
Unanswered
PepeW posted this in #help-forum
PepeWOP
I have this graphql client:
The thing is that, when I call my function like I used to, it doesn't work (I can still see 2 request being triggered):
But now if I do this, it works (only one request being triggered):
I know that now it works because the object reference is the same. The problem is that this example is quite simple but most of the time I will not be able to create an object before hand.
So is there a way to modify my
import { cache } from "react"
interface GraphqlRequestParameters<T, V> {
document: RequestDocument | TypedDocumentNode<T, V>
variables?: V
withAuth?: boolean
requestHeaders?: GraphQLClientRequestHeaders
onError?: (error: unknown) => void
}
export async function graphqlServerRequest<T, V extends Variables = Variables>({
document,
variables,
withAuth = false,
requestHeaders,
onError,
}: GraphqlRequestParameters<T, V>): Promise<T | undefined> {
try {
if (withAuth) {
return await graphqlServerWithAuth.request(document, variables, requestHeaders)
} else {
return await graphqlServerWithoutAuth.request(document, variables, requestHeaders)
}
} catch (error) {
if (onError) onError(error)
else throw error
}
}
export const cachedGraphqlServerRequest = cache(graphqlServerRequest)The thing is that, when I call my function like I used to, it doesn't work (I can still see 2 request being triggered):
// page.tsx
await cachedGraphqlServerRequest({
document: someQuery,
withAuth: true,
variables: { slug },
onError() {
notFound()
},
})
await cachedGraphqlServerRequest({
document: someQuery,
withAuth: true,
variables: { slug },
onError() {
notFound()
},
})But now if I do this, it works (only one request being triggered):
// page.tsx
const param = {
document: someQuery,
withAuth: true,
variables: { slug },
onError() {
notFound()
},
}
await cachedGraphqlServerRequest(param)
await cachedGraphqlServerRequest(param)I know that now it works because the object reference is the same. The problem is that this example is quite simple but most of the time I will not be able to create an object before hand.
So is there a way to modify my
cachedGraphqlServerRequest so I can keep calling my the function with the object as a parameter ?1 Reply
PepeWOP
up