GraphQL 突变中的 onError

onError in GraphQL mutations

我正在尝试 graphql 突变的 onError 并意识到它们无法正常工作:

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

那么捕获错误还有什么办法呢?在上一个问题中,我被告知使用 try catch 块进行突变并不是一个好主意。

我正在尝试做这样的事情,有一个可能的解决方法:

我要求用户输入,然后 运行 查询。根据查询的结果,我渲染了一些 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],
  );


    if (!addingContactLoading && isMutationCalled) {
    if (addingContactError) {
      console.log('this is the error', addingContactError);
      if ((addingContactError.toString()).includes('already exists')){
        Alert.alert('Contact Already Exists');
      }
      else{
      Alert.alert('Unable to Add Contact');
      }
    }
  }

  return (
...
)
 <User onAddContact={onAddContact} data={userData}></User>
...
export const User: React.FunctionComponent<UserProps> = ({
  data,
  onAddContact,
}) => {
  if (!data) return null;
  return (
                <Button
                  onPress={() => onAddContact(Number(item.id))}
                  >
                </Button>

一般来说,这个过程工作正常,但当突变中出现 Alert.alert('Contact Already Exists'); 错误时,就会产生问题。例如,在我关闭错误警报和 运行 一个新查询后,我应该只获得新的用户组件(即使我现在只是 运行 查询,而不是突变) .但是,我也收到 Contact Already Added 警报。事实上它弹出了两次。

也许问题出在回调中。

像这样使用 .catch 可以,但是没有其他方法可以做到这一点吗?由于我没有使用 catch 进行查询,因此代码会变得不一致。

.catch((err: any) => {
      console.log('errror', err)
      if ((err.toString()).includes('already exists')){
        console.log('working')
        Alert.alert('Contact Already Exists');
      }
      else{
      Alert.alert('Unable to Add Contact');
      }
    });

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

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 记忆组件以避免不必要的重新渲染此组件