Ad

How To Use Mutations In React-apollo-hooks And Formik?

In my many attempts, I've tried to use react-apollo-hooks and formik together but it seems impossible. The data from the forms is only available in the <Formik> tag, and is otherwise inaccessible outside of it. Also I can't call my useMutation hook and pass arguments to it at the same time:

const SignUp = () => {
  const classes = useStyles();
  // The react-apollo-hook for useMutation
  // Its not hard to call this, but it seems impossible to call it,
  // with any sort of arguments.
  // It seems pointless not being able to pass in data from the form
  const [createUser, { loading }] = useMutation(CREATE_USER_MUTATION, {
    variables: {
      firstName: '???',
      lastName: '???',
      email: '???',
      password: '???',
    },
  });
  // Formik stuff goes down here. It's impossible to call `useMutation` 
  // with the argument of `values`
  return (
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
        password: '',
        showPassword: false,
      }}
      // This is the part that calls the hook.
      // I see no way of passing arguments to `useMutation` from here
      onSubmit={(values, { setSubmitting }) => createUser}
      render={({submitForm, isSubmitting, values, setFieldValue}) => (
        <div>
          <h1>Sign up for a new account</h1>
          <Form className={classes.container}>
            <Field
              className={classes.textField}
              name="firstName"
              type="text"
              label="First name"
              margin="dense"
              variant="outlined"
              component={TextField}
            />
          </Form>
          <Button
            variant="contained"
            color="primary"
            margin="dense"
            className={classes.button}
            disabled={isSubmitting}
            onClick={submitForm}
          >
            Sign Up
          </Button>
        </div>
      )}
    />
  );

};

So how would I somehow be able to pass arguments to the useMutation part at the top, from onSubmit? It seems impossible to pass arguments to the hook. I don't think I can add any other data outside of the query name CREATE_USER_MUTATION and the objects which has the settings.

Ad

Answer

Mutation variables can be provided to the individual mutation call instead of the useMutation call. So you can do this at the top of your component:

const [createUser, { loading }] = useMutation(CREATE_USER_MUTATION)

and then provide the variables once you actually call createUser:

onSubmit={(values, { setSubmitting }) => createUser({ variables: values })}
Ad
source: stackoverflow.com
Ad