DEV Community

Discussion on: You don't really need Apollo

Collapse
 
viralsangani profile image
Viral Sangani • Edited

Hey, I was following your suggestion of useSWR in graphql, but I got stuck. I want to send a graphql request onPress event.
I tried the this,

const [shouldFetch, setShouldFetch] = React.useState(false)
Enter fullscreen mode Exit fullscreen mode
const { data } = useSWR(
    shouldFetch
        ? [query, { firstName, lastName, email, password1, password2 }]
        : null,
        gqlFetcher
    )
Enter fullscreen mode Exit fullscreen mode

Didn't work. How do I send Graphql request onPress() with useSWR??

Collapse
 
pabloabc profile image
Pablo Berganza • Edited

Hey! I don't see anything particularly wrong on what you're showing me here. So whatever is causing you an issue should be somewhere else?

I just quickly made you a Codesandbox showing how to do this here.

Note that useMemo is necessary here since it prevents a new variables object from being created if name does not change. If it weren't there, every time the component re-rendered a new request to the GraphQL API would be made creating an infinite loop in some cases.

Collapse
 
viralsangani profile image
Viral Sangani

Thank you so much, It helped a lot. I was not using useMemo, and getting in the loop.

Thread Thread
 
pabloabc profile image
Pablo Berganza

I'm glad I could help!

Yeah that's a little detail to remember. Since useSWR shallowly compares each argument, and each newly created object's reference is different, you have to make sure to pass the same reference (not create a new object) if you don't want a re-fetch.

Collapse
 
sortbyrandom profile image
sort by random

Thanks for the tip to use useMemo. I was getting into an infinite loop as well, and had no idea what to do.