如何在 react-native 应用程序中的 apollo-link-error 上注销用户?

Sai*_*Akh 8 react-native apollo-client react-navigation

为了在我的 react-native 应用程序中导航,我使用了“react-navigation”。

使用下面的代码,我可以成功拦截来自服务器的所有必要错误。

const linkError = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    // Logout user
    // 1. Issue logout mutation
    // 2. Navigate to Login screen
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    );
  }
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const client = new ApolloClient({
  link: ApolloLink.from([linkError, stateLink, authLink, httpLink]),
  cache,
});
Run Code Online (Sandbox Code Playgroud)

问题是如何将用户导航到“登录”屏幕并在发生错误时发出“注销”突变?

Vla*_*tko 0

您可以重写代码以client从挂钩返回。它可能类似于:

export const useApolloClient = () => {
  // Assuming `logout` is a function that removes the user token
  const { logout } = useAuth();

  return useMemo(() => {
    const linkError = onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        graphQLErrors.map(({ message, locations, path }) => {
          if (message === 'Unauthorized') {
            // Or whatever may be the reason for logging out
            logout()
          }

          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
          )
        });
      }
      if (networkError) console.log(`[Network error]: ${networkError}`);
    });

    return new ApolloClient({
      link: ApolloLink.from([linkError, stateLink, authLink, httpLink]),
      cache,
    });
  }, [logout]);
};
Run Code Online (Sandbox Code Playgroud)

针对您的评论补充几点:

// 注销用户 // 1. 发出注销突变

不确定你的意思logout mutation- 我想你存储了代表登录用户的令牌。

// 2. 导航到登录屏幕

如果您使用react-navigation,我认为手动导航不是一个好的做法。根据他们的文档,您应该简单地返回Login screen基于isSignedIn. 我建议使用 JWT 令牌(如果这是假定的流程)作为标志isSignedIn