2017-12-27 42 views
1

을 사용하면 currentUser 쿼리를 실행하고 캐시에서 토큰을 볼 수 있지만 앱을 새로 고침하면 토큰이 반환됩니다. null .실제로 로그인 할 때 apollo-cache-persist 및 apollo-link-state가 정의되지 않은 캐시 상태로 끝나는

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, 
}); 

답변

1

을 확인해 싶다면 나는 아폴로 - 링크 상태에 대한 기사를 작성하고 당신의 쿼리가 캐시 전에 실행되어있을 수 있습니다 재수 화되었습니다.

캐시가 복원되면 해결되는 약속을 반환하는 persistCache을 기다릴 수 있습니다.