【问题标题】:How to use mutations in react-apollo-hooks and formik?如何在 react-apollo-hooks 和 formik 中使用突变?
【发布时间】:2019-11-28 06:49:36
【问题描述】:

在我的许多尝试中,我尝试过将 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 和具有设置的对象之外添加任何其他数据。

【问题讨论】:

    标签: reactjs graphql react-hooks formik react-apollo-hooks


    【解决方案1】:

    可以将突变变量提供给单个突变调用,而不是 useMutation 调用。因此,您可以在组件的顶部执行此操作:

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

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

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

    【讨论】:

    • 我之前找到了一个解决方法,它依赖于一些低效的东西,依赖于使用 React useState,在 onSubmit 函数中设置所有字段,并使用 useEffect 调用 createUser 毕竟只有字段已更新(因为它是异步的)。但它显然效率低下并且需要大量代码行。您的解决方案更加简洁明了!
    猜你喜欢
    • 2020-01-11
    • 2021-05-01
    • 2020-09-18
    • 2019-09-14
    • 2018-09-26
    • 2020-06-21
    • 1970-01-01
    • 2019-09-17
    • 2020-06-19
    相关资源
    最近更新 更多