问题
I am trying to access Formik values
globally so that I can add values.email
to the dependency array of my handleSubmitForm
. I read about useFormikContext() and am trying to use it but I am unable to.
If I add it after handleSubmitForm
, I get an error that: Object is of type 'unknown'
. To overcome this, I changed this
const { values} = useFormikContext();
to this:
const values: FormValues = useFormikContext();
but then I get an error on values that:
Property 'email' is missing in type 'FormikSharedConfig<{}> & FormikState<unknown> & FormikHelpers<unknown> & FormikHandlers & FormikComputedProps<unknown> & FormikRegistration & { ...; } & Pick<...>' but required in type 'FormValues'.ts(274
Here's what my code looks like:
export const Page: React.FunctionComponent<PageProps> = ({
toggleShowPage,
showAddFriendEmailPage,
}) => {
const initialValues: FormValues = {
email: '',
};
const [userData, setUserData] = useState<UsersLazyQueryHookResult>('');
const [numberOfUsers, setNumberOfUsers] = useState('');
const { values} = useFormikContext();
const validationSchema = emailValidationSchema;
const showUsers = React.useCallback(
(data: UsersLazyQueryHookResult, numberOfUsers: Number) => {
for (var i = 0; i < numberOfUsers; i++) {
console.log('Number of Users in Loop: ', numberOfUsers);
const userId = data.users.nodes[i].id;
const userName = data.users.nodes[i].firstName
.concat(' ')
.concat(data.users.nodes[i].lastName);
return (
<View style={styles.friends}>
<View style={styles.item}>
<Text style={styles.userName}>{userName}</Text>
<Button style={styles.addButton}
onPress={() => addFriend(Number(data.users.nodes[i].id))}
>
</Button>
</View>
</View>
);
}
},
[createUserRelationMutation],
);
const addFriend = React.useCallback(
(id: Number) => {
console.log('Whats the Id', id);
createUserRelationMutation({
variables: {
input: { relatedUserId: id, type: RelationType.Friend, userId: 7 },
},
});
},
[createUserRelationMutation],
);
const getFriendId = React.useCallback(
(data: UsersLazyQueryHookResult) => {
if (data) {
if (data.users.nodes.length == 0) {
Alert.alert('User Not Found');
} else {
setUserData(data);
setNumberOfUsers(data.users.nodes.length);
}
}
},
[addFriend],
);
const [loadUsers] = useUsersLazyQuery({
onCompleted: getFriendId,
onError: _onLoadUserError,
});
const handleSubmitForm = React.useCallback(
(values: FormValues, helpers: FormikHelpers<FormValues>) => {
console.log('Submitted');
loadUsers({
variables: {
where: { email: values.email },
},
});
values.email = '';
},
[loadUsers],
);
return (
<Modal
visible={showAddFriendEmailPage}
animationType="slide"
transparent={true}>
<SafeAreaView>
<View style={styles.container}>
<View style={styles.searchTopContainer}>
<View style={styles.searchTopTextContainer}>
<Text
style={styles.searchCancelDoneText}
onPress={toggleShowPage}>
Cancel
</Text>
<Text style={styles.searchTopMiddleText}>
Add Friend by Email
</Text>
<Text style={styles.searchCancelDoneText}>Done</Text>
</View>
<View>
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={validationSchema}>
{({ handleChange, handleBlur, handleSubmit, values }) => (
<View style={styles.searchFieldContainer}>
<View style={styles.form}>
<FieldInput
handleChange={handleChange}
handleBlur={handleBlur}
value={values.email}
fieldType="email"
/>
<ErrorMessage
name="email"
render={msg => (
<Text style={styles.errorText}>{msg}</Text>
)}
/>
</View>
<View style={styles.buttonContainer}>
<Button
rounded
style={styles.button}
onPress={handleSubmit}>
<Text style={styles.text}>Search </Text>
</Button>
</View>
</View>
)}
</Formik>
</View>
{showUsers(userData, Number(numberOfUsers))}
</View>
</View>
</SafeAreaView>
</Modal>
);
};
Why am I trying to add it to the dependency array?
Basically, I have a Formik form where I enter an email address, run a graphql query accordingly, display some results and then run a mutation. Currently, this works successfully on the first attempt. However, when I try to re-enter an email address and submit the form again, I am unable to click on the button. It's disabled somehow. So trying to fix that.
However, when I click on the button within the new rendered object, and the mutation happens, the rendered object disappears (intentionally) and now I can again type in my field and submit the form.
If I just use this:
[loadUsers, values],
My app crashes with Type Error: Undefined is not an object
I also tried
const { values: FormValues } = useFormikContext();
but it gives me Cannot find name 'values'
. If I hover over the deconstruction, I get 'FormValues' is declared but its value is never read.ts(6133)
来源:https://stackoverflow.com/questions/61755659/access-values-globally-with-useformikcontext