0

So, I've been searching the internet for an example of a react-query function called outside the body of the function component; however, I was unable to find a sample.

I have a query type of GraphQL, and I am waiting for a value from the form that I could pass on. So I needed to call it inside the onSubmit function of Formik.

I have generated my hooks with GraphQL Codegen. Since we cannot call the react-hooks outside the function, I am uncertain how I can do this.

So, this is my react-hook for the query

const [{ data, fetching, stale, error, extensions, operation }] = useForgotPasswordQuery({ variables: { email: "value from the form" } });

Unlike with the mutation, it returns a function wherein I could use to call outside the function.

const [, forgotPassword] = useForgotPasswordMutation();

...
<Formik initialValues={{ email: '' }} onSubmit={async (values, { setErrors }) => {
    const response = await forgotPassword({ email: values.email });
}}>

I'd like to know on this use case, I cannot use query type? Or this is a way that I am unaware.

I've read here in the Stackoverflow that the convention:

Query — for querying data (SELECT operations)

Mutation — for creating new and updating/deleting existing data (INSERT, UPDATE, DELETE)

In a way, this convention makes sense to me and I want to implement it. So I am trying to do it using the query rather than the mutation.

Rich
  • 3,928
  • 4
  • 37
  • 66
  • Would the ‘enabled’ option of a query be any help? To run it based on some conditio. – Jakub Kotrs Apr 18 '22 at 17:23
  • @JakubKotrs, sorry, what `enabled` option are you talking about? – Rich Apr 18 '22 at 17:24
  • The useQuery hook accepts “enabled” as option. Your question sounded like you want to delay a query until a certain condition is met and enabled option is ideal for that. – Jakub Kotrs Apr 18 '22 at 17:25
  • Oh, you mean the `pause`, @JakubKotrs? Hmm, I thought this has something to do with the SSR. I am not sure what's the `enabled` property you are referring to. I checked the properties being accepted to the generated query method, and I cannot see it. – Rich Apr 18 '22 at 17:28
  • No, it’s enabled, see here https://react-query.tanstack.com/reference/useQuery – Jakub Kotrs Apr 18 '22 at 17:35
  • I'm having a hard time understanding what the issue was with the `useMutation`. What you have read is also true for `react-query` https://react-query.tanstack.com/guides/mutations – Gerardo Sabetta Apr 19 '22 at 21:27

0 Answers0