首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在react-apollo-hooks和formik中使用突变?

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

Stack Overflow用户
提问于 2019-07-19 17:38:24
回答 1查看 1.8K关注 0票数 5

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

代码语言:javascript
复制
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和具有这些设置的对象之外,我不认为我可以添加任何其他数据。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-19 19:02:40

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

代码语言:javascript
复制
const [createUser, { loading }] = useMutation(CREATE_USER_MUTATION)

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

代码语言:javascript
复制
onSubmit={(values, { setSubmitting }) => createUser({ variables: values })}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57109680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档