Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6212

Use Formik When GraphQL Queries Are Already Used

$
0
0

I had a native base's input field which reads a value that is then used in a graphql query and mutation. I wanted to add Formik Validation to it. I read that in order to use Formik validation, I would need to use Fieldinstead of Input.

This is my code logic, which works without Formik validation so far. Here I am using useState instead of Formik values. The handleSubmithappens onPressof the button:

type AddFriendEmailPageProps = {  toggleShowPage: () => void;  showAddFriendEmailPage: boolean;};export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({  toggleShowPage,  showAddFriendEmailPage,}) => {  const [friendEmail, setFriendEmail] = useState('');  const [errorMessage, setErrorMessage] = useState('');  const validationSchema = emailValidationSchema;   const showAlert = () => {    Alert.alert('Friend Added');  }  useEffect(() => {    if (showAddFriendEmailPage) return;    setFriendEmail('');  }, [showAddFriendEmailPage]);  const _onLoadUserError = React.useCallback((error: ApolloError) => {    setErrorMessage(error.message);    Alert.alert('Unable to Add Friend');  }, []);  const [    createUserRelationMutation,    {      data: addingFriendData,      loading: addingFriendLoading,      error: addingFriendError,      called: isMutationCalled,    },  ] = useCreateUserRelationMutation({    onCompleted : ( data: any) => {      showAlert();    }  });  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: any) => {      console.log('Email', friendEmail);      if (data) {        if (data.users.nodes.length == 0) {          setErrorMessage('User Not Found');        } else {          addFriend(Number(data.users.nodes[0].id));        }      }    },    [friendEmail, addFriend],  );  const [loadUsers] = useUsersLazyQuery({    onCompleted: getFriendId,    onError: _onLoadUserError,  });  const handleSubmit = React.useCallback(() => {    loadUsers({      variables: {        where: { email: friendEmail },      },    });    setFriendEmail('');  }, [loadUsers, friendEmail]);  }  return (<Modal      visible={showAddFriendEmailPage}      animationType="slide"      transparent={true}><SafeAreaView><View style={scaledAddFriendEmailStyles.container}><View style={scaledAddFriendEmailStyles.searchTopContainer}><View style={scaledAddFriendEmailStyles.searchTopTextContainer}><Text                style={scaledAddFriendEmailStyles.searchCancelDoneText}                onPress={toggleShowPage}>                Cancel</Text><Text style={scaledAddFriendEmailStyles.searchTopMiddleText}>                Add Friend by Email</Text><Text style={scaledAddFriendEmailStyles.searchCancelDoneText}>                Done</Text></View><View style={scaledAddFriendEmailStyles.searchFieldContainer}><Item style={scaledAddFriendEmailStyles.searchField}><Input                  placeholder="Email"                  style={scaledAddFriendEmailStyles.searchText}                  onChangeText={(text) => setFriendEmail(text)}                  value={friendEmail}                  autoCapitalize="none"                /></Item><View style={scaledAddFriendEmailStyles.buttonContainer}><Button                  onPress={() => handleSubmit()}><Text style={scaledAddFriendEmailStyles.text}>                    Add Friend{''}</Text></Button></View></View></View></View></SafeAreaView></Modal>  );};

Now I am trying to add Formik. But I want to somehow use the same handleSubmit. Otherwise, the hooks and logic might get messed up. This is what I was trying:

export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({  toggleShowPage,  showAddFriendEmailPage,}) => {  const initialValues: FormValues = {    friendEmail: '',  };  const [errorMessage, setErrorMessage] = useState('');  const validationSchema = emailValidationSchema;   useEffect(() => {    if (showAddFriendEmailPage) return;    initialValues.friendEmail = '';  }, [showAddFriendEmailPage]);  const _onLoadUserError = React.useCallback((error: ApolloError) => {    setErrorMessage(error.message);    Alert.alert('Unable to Add Friend');  }, []);  const [    createUserRelationMutation,    {      data: addingFriendData,      loading: addingFriendLoading,      error: addingFriendError,      called: isMutationCalled,    },  ] = useCreateUserRelationMutation({    onCompleted : ( data: any) => {      showAlert();    }  });  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: any) => {      console.log('Email', friendEmail);      if (data) {        if (data.users.nodes.length == 0) {          console.log('No user');        } else {          addFriend(Number(data.users.nodes[0].id));        }      }    },    [friendEmail, addFriend],  );  const [loadUsers] = useUsersLazyQuery({    onCompleted: getFriendId,    onError: _onLoadUserError,  });  const handleSubmit = React.useCallback((    values: FormValues,    helpers: FormikHelpers<FormValues>,    ) => {    console.log('Submitted');    loadUsers({      variables: {        where: { email: values.friendEmail },      },    });    //setFriendEmail('');    values.friendEmail = '';  }, [loadUsers, friendEmail]);  if (!addingFriendLoading && isMutationCalled) {    if (addingFriendData) {      console.log('Checking');      console.log(addingFriendData);    }    if (addingFriendError) {      console.log('errorFriend', addingFriendError.message);      setErrorMessage(addingFriendError.message);      Alert.alert('Unable to Add Friend');    }  }  return (<Modal      visible={showAddFriendEmailPage}      animationType="slide"      transparent={true}><SafeAreaView><View style={scaledAddFriendEmailStyles.container}><View style={scaledAddFriendEmailStyles.searchTopContainer}><View style={scaledAddFriendEmailStyles.searchTopTextContainer}><Text                style={scaledAddFriendEmailStyles.searchCancelDoneText}                onPress={toggleShowPage}>                Cancel</Text><Text style={scaledAddFriendEmailStyles.searchTopMiddleText}>                Add Friend by Email</Text><Text style={scaledAddFriendEmailStyles.searchCancelDoneText}>                Done</Text></View><View style={scaledAddFriendEmailStyles.searchFieldContainer}><Formik                initialValues={initialValues}                onSubmit={handleSubmit}                validationSchema={validationSchema}>                {({                  handleChange,                  handleBlur,                  handleSubmit,                  isSubmitting,                  values,                }) => ( <Field                  component={Input}                  placeholder="Email"                  onChangeText={handleChange('friendEmail')}                  onBlur={handleBlur('friendEmail')}                  value={values.friendEmail}                  autoCapitalize="none"                  />                )}<View style={scaledAddFriendEmailStyles.buttonContainer}><Button                  rounded                  style={scaledAddFriendEmailStyles.button}                ><Text style={scaledAddFriendEmailStyles.text}>                    Add Friend{''}</Text></Button></View></Formik></View></View></View></SafeAreaView></Modal>  );};

Currently, this is not working for me. For example, I need to access these values [friendEmail, addFriend], at the end of getFriendId but I am unable to pass values, helpers as a parameter.

Similarly, at the end of handleSubmit, I need to use [loadUsers, friendEmail]);

values.friendEmail works inside the function but how can I access the value outside it? Here, if I use this, I will just get Cannot find name 'values'.


Viewing all articles
Browse latest Browse all 6212

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>