为了账号安全,请及时绑定邮箱和手机立即绑定

图QL突变中的错误

图QL突变中的错误

森林海 2022-09-23 16:29:44
我正在尝试图形ql突变的错误,并意识到它们无法正常工作:https://github.com/apollographql/apollo-client/issues/5708那么,对于捕获错误,还可以做些什么呢?在上一个问题中,我被告知使用尝试捕获块进行突变不是一个好主意。我正在尝试执行类似操作,并可能有一个解决方法:我要求用户输入,然后运行查询。根据查询结果,我呈现一些组件。在用户组件中,我使用按钮来运行突变。Userexport const AddContact: React.FunctionComponent = () => {  const initialValues: FormValues = {    phoneNumber: '',  };  const [isSubmitted, setIsSubmitted] = useState(false);  const [userData, setUserData] = useState<UsersLazyQueryHookResult>('');  const navigation = useNavigation();  const validationSchema = phoneNumberValidationSchema;  const _onLoadUserError = React.useCallback((error: ApolloError) => {    Alert.alert('Unable to Add Contact');  }, []);  const [    createUserRelationMutation,    {      data: addingContactData,      loading: addingContactLoading,      error: addingContactError,      called: isMutationCalled,    },  ] = useCreateUserRelationMutation({    onCompleted: () => {      Alert.alert('Contact Added');    },  });    const onAddContact = (id: number) => {    setIsSubmitted(false);    setUserData(null);    createUserRelationMutation({      variables: {        input: { relatedUserId: id, type: RelationType.Contact, userId: 1 },      },    });  }  const getContactId = React.useCallback(    (data: UsersLazyQueryHookResult) => {      if (data) {        if (data.users.nodes.length == 0) {          Alert.alert('No User Found');        } else {          setUserData(data);        }      }    },    [onAddContact],  );  const [loadUsers] = useUsersLazyQuery({    onCompleted: getContactId,    onError: _onLoadUserError,  });  const handleSubmitForm = React.useCallback(    (values: FormValues, helpers: FormikHelpers<FormValues>) => {      setIsSubmitted(true);      const plusSign = '+';      const newPhoneNumber = plusSign.concat(values.phoneNumber);      console.log('Submitted');      loadUsers({        variables: {          where: { phoneNumber: newPhoneNumber },        },      });      helpers.resetForm();    },    [loadUsers],  );
查看完整描述

1 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

您可以使用回调,而不是直接从函数体上的结果检查属性,如下所示onErroraddingContactError


const _onCreateUserRelationError = React.useCallback((error: ApolloError) => {

    console.log('this is the error', error);

    Alert.alert(error.message.includes('already exists') ? 'Contact Already Exists' : 'Unable to Add Contact');

}, []);


const [

    createUserRelationMutation,

    {

        data: addingContactData,

        loading: addingContactLoading,

        called: isMutationCalled,

    },

] = useCreateUserRelationMutation({

    onCompleted: () => {

        Alert.alert('Contact Added');

    },

    onError: _onCreateUserRelationError

});

注: 使用 记住组件以避免此组件的不必要重新渲染React.memo


查看完整回答
反对 回复 2022-09-23
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信