title: How to implement auto jwt token refresh before every graphql request with Apollo and React Native?
body: <p>I would like to implement auto refresh jwt token before every request to <strong>GraphQL</strong> with <strong>Apollo</strong> middleware in <strong>React Native</strong> app. After every user login he gets two tokens: access and refresh. Access token it is the short one for 30-60 min for using in authorization header. And refresh token it is the long one for 60 days for confirm of refresh token graphql mutation. 
  My flow:</p>
  
  <ol>
  <li>User login and gets 2 tokens -> put access token to authorization header with <strong>Appollo</strong> setContext.</li>
  <li>User make request to <strong>GraphQL</strong> -> check expireTime of accessToken on a client side:
  -> if it is not expired -> confirm request
  -> if it is has expired -> call <strong>GraphQL</strong> refreshToken mutation -> get new tokens -> confirm request.
  For keeping tokens on the client side i use <strong>KeyChain</strong> storage. Can you tell me please should i use <strong>Apollo</strong> cache for keeping tokens too? Should i write <strong>Apollo</strong> state for tokens? And how i can implement my flow?</li>
  </ol>
  
  <p>GraphQL mutation</p>
  
  <pre><code>mutation UpdateTokens($refreshToken: String!, $refreshTokenId: String!) 
   {
      updateTokens(refreshToken: $refreshToken, refreshTokenId: $refreshTokenId) {
        user {
          name
          phone
        }
        accessToken
        refreshToken
      }
    }
  </code></pre>
  
  <p>App.js</p>
  
  <pre><code>import React from 'react'
  import { ApolloClient } from 'apollo-client'
  import { ApolloLink } from 'apollo-link'
  import { ApolloProvider } from 'react-apollo'
  import { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'
  import { createHttpLink } from 'apollo-link-http'
  import { InMemoryCache } from 'apollo-cache-inmemory'
  import { setContext } from 'apollo-link-context'
  import * as Keychain from 'react-native-keychain'
  import AppNavigator from './AppNavigator'
  
  const httpLink = createHttpLink({
    uri: 'http://localhost:4000'
  })
  
  const cache = new InMemoryCache()
  
  const authLink = setContext(async (req, { headers, ...context }) =&gt; {
    const tokens = await Keychain.getGenericPassword()
    const accessToken = tokens.username
    return {
      headers: {
        ...headers,
        authorization: accessToken ? `Bearer ${accessToken}` : ''
      },
      ...context
    }
  })
  
  const client = new ApolloClient({
    link: ApolloLink.from([authLink, httpLink]),
    cache,
    connectToDevTools: true
  })
  
  const App = () =&gt; {
    return (
      &lt;ApolloProvider client={client}&gt;
        &lt;ApolloHooksProvider client={client}&gt;
          &lt;AppNavigator /&gt;
        &lt;/ApolloHooksProvider&gt;
      &lt;/ApolloProvider&gt;
    )
  }
  
  export default App
  </code></pre>