图QL突变中的错误

我正在尝试图形ql突变的错误,并意识到它们无法正常工作:

https://github.com/apollographql/apollo-client/issues/5708

那么,对于捕获错误,还可以做些什么呢?在上一个问题中,我被告知使用尝试捕获块进行突变不是一个好主意。

我正在尝试执行类似操作,并可能有一个解决方法:

我要求用户输入,然后运行查询。根据查询结果,我呈现一些组件。在用户组件中,我使用按钮来运行突变。User

export 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],

  );


森林海
浏览 107回答 1
1回答

烙印99

您可以使用回调,而不是直接从函数体上的结果检查属性,如下所示onErroraddingContactErrorconst _onCreateUserRelationError = React.useCallback((error: ApolloError) => {&nbsp; &nbsp; console.log('this is the error', error);&nbsp; &nbsp; Alert.alert(error.message.includes('already exists') ? 'Contact Already Exists' : 'Unable to Add Contact');}, []);const [&nbsp; &nbsp; createUserRelationMutation,&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; data: addingContactData,&nbsp; &nbsp; &nbsp; &nbsp; loading: addingContactLoading,&nbsp; &nbsp; &nbsp; &nbsp; called: isMutationCalled,&nbsp; &nbsp; },] = useCreateUserRelationMutation({&nbsp; &nbsp; onCompleted: () => {&nbsp; &nbsp; &nbsp; &nbsp; Alert.alert('Contact Added');&nbsp; &nbsp; },&nbsp; &nbsp; onError: _onCreateUserRelationError});注: 使用 记住组件以避免此组件的不必要重新渲染React.memo
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript