在我的许多尝试中,我尝试将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>
)}
/>
);
};
那么我如何才能将参数从useMutation
传递到顶部的onSubmit
呢?似乎不可能将参数传递给该钩子。我认为我无法添加查询名称CREATE_USER_MUTATION
和具有设置的对象之外的其他任何数据。
答案 0 :(得分:1)
可以将突变变量提供给各个突变调用,而不是useMutation
调用。因此,您可以在组件顶部执行此操作:
const [createUser, { loading }] = useMutation(CREATE_USER_MUTATION)
,然后在您实际调用createUser
后提供变量:
onSubmit={(values, { setSubmitting }) => createUser({ variables: values })}