当我实际登录时,我可以运行currentUser查询并在缓存中查看令牌,但当我刷新应用时,令牌返回null
。
const currentUser = {
defaults: {
currentUser: {
__typename: 'CurrentUser',
token: null,
},
},
resolvers: {
Mutation: {
updateCurrentUser: (_, { token }, { cache }) => {
cache.writeData({
data: {
__typename: 'Mutation',
currentUser: {
__typename: 'CurrentUser',
token,
},
},
});
return null;
},
},
},
};
export default currentUser;
我的客户端设置代码如下所示:
import { AsyncStorage } from 'react-native';
import {
ApolloClient,
HttpLink,
InMemoryCache,
IntrospectionFragmentMatcher,
} from 'apollo-client-preset';
import { Actions as RouterActions } from 'react-native-router-flux';
import { persistCache } from 'apollo-cache-persist';
import { propEq } from 'ramda';
import { setContext } from 'apollo-link-context';
import { withClientState } from 'apollo-link-state';
import fragmentTypes from './data/fragmentTypes';
import config from './config';
import { onCatch } from './lib/catchLink';
import { defaults, resolvers } from './resolvers';
import { CurrentUserQuery } from './graphql';
const cache = new InMemoryCache({
fragmentMatcher: new IntrospectionFragmentMatcher({
introspectionQueryResultData: fragmentTypes,
}),
});
persistCache({
cache,
storage: AsyncStorage,
trigger: 'write',
});
const httpLink = new HttpLink({
uri: `${config.apiUrl}/graphql`,
});
const stateLink = withClientState({ cache, resolvers, defaults });
const contextLink = setContext((_, { headers }) => {
const { currentUser: { token } } = cache.readQuery(CurrentUserQuery());
return {
headers: {
...headers,
authorization: token && `Bearer ${token}`,
},
};
});
const catchLink = onCatch(({ networkError = {} }) => {
if (propEq('statusCode', 401, networkError)) {
// remove cached token on 401 from the server
RouterActions.unauthenticated({ isSigningOut: true });
}
});
const link = stateLink
.concat(contextLink)
.concat(catchLink)
.concat(httpLink);
export default new ApolloClient({
link,
cache,
});
答案 0 :(得分:1)
重新缓冲缓存是一种异步操作,可能是在缓存重新水化之前您的查询正在执行。
您可以等待persistCache
返回一个缓存恢复后解析的承诺。
答案 1 :(得分:0)
可能尝试使用Apollo Link软件包加入链接。
import {ApolloLink} from 'apollo-link';
//....
//....
//....
const link = ApolloLink.from([stateLink,contextLink, catchLink, httpLink]);
PS:如果你想查看一下,我写了一篇关于apollo-link-state的文章https://hptechblogs.com/central-state-management-in-apollo-using-apollo-link-state/