当我实际登录时,我可以运行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,
});发布于 2018-01-14 21:23:42
恢复缓存消重是一个异步操作,您的查询可能在缓存恢复消重之前执行。
您可以等待persistCache,它会返回一个promise,一旦缓存恢复,这个promise就会解析。
发布于 2017-12-28 14:52:22
也许可以尝试使用Apollo Link包来加入这些链接。
import {ApolloLink} from 'apollo-link';
//....
//....
//....
const link = ApolloLink.from([stateLink,contextLink, catchLink, httpLink]);PS:我已经写了一篇关于阿波罗-链路状态的文章,如果你想看看它,https://hptechblogs.com/central-state-management-in-apollo-using-apollo-link-state/
https://stackoverflow.com/questions/47999808
复制相似问题