如何在 react-apollo-hooks 和 formik 中使用突变?

How to use mutations in react-apollo-hooks and formik?

在我的多次尝试中,我尝试过同时使用 react-apollo-hooks 和 formik,但这似乎是不可能的。来自表单的数据仅在 <Formik> 标记中可用,否则无法在其外部访问。我也不能调用我的 useMutation 钩子并同时向它传递参数:

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>
      )}
    />
  );

};

那么我怎样才能以某种方式将参数从 onSubmit 传递到顶部的 useMutation 部分?似乎不可能将参数传递给钩子。我不认为我可以在查询名称 CREATE_USER_MUTATION 和具有设置的对象之外添加任何其他数据。

突变变量可以提供给单独的突变调用而不是 useMutation 调用。所以你可以在你的组件的顶部这样做:

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

然后在您实际调用后提供变量 createUser:

onSubmit={(values, { setSubmitting }) => createUser({ variables: values })}