Hello all, I’m having a problem with my apollo cli...
# orm-help
r
Hello all, I’m having a problem with my apollo client refetching all my queries on
resetStore()
before my auth token has a chance to update on login. I imagine this is a common problem if I do a
setTimeout
wrapping around
resetStore
after the login for a second or so I get my app to kick me to the home screen after login, but without it I just stay on the login screen and I only get to the home screen after a refresh when it then picks up the token (I’m on react native) is there a common pattern for dealing with this?
m
@ryanmagoon why do you run
resetStore()
during login?
If someone has loaded the web app, there is no store and when someone logs out, I run
client.cache.reset()
to reset the cache.
r
that’s cool. I ended up putting my
setContext
with the auth stuff in the
request
param in apollo
Copy code
const client = new ApolloClient({
  request: async operation => {
    const token = await getToken()
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : ''
      }
    })
  },
  uri: '<http://localhost:4000>'
})
I think I’m still missing something though, I agree that I shouldn’t have to reset the store on login
Copy code
const NavWrapper = ({ loading, me }) => {
  if (loading) {
    return (
      <SafeAreaView style={{ flex: 1, justifyContent: 'center' }}>
        <ActivityIndicator size="large" />
      </SafeAreaView>
    )
  }

  return me ? <AppStack /> : <AuthStack />
}
const userQuery = gql`
  query userQuery {
    me {
      id
      email
      name
    }
  }
`

export default graphql(userQuery, {
  props: ({ data }) => ({ ...data })
})(NavWrapper)
this is the component that was re running the query before the new token was up and going in the client
m
Copy code
//use the Token in localStorage for authorized requests
const middlewareLink = setContext(() => ({
  headers: { authorization: localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : null }
}));

// const httpLink = createHttpLink({ uri: `http://${process.env.API_URL}` });
const httpLink = createHttpLink({ 
  uri: process.env.API_URL,
  batchInterval: 100
});

const link = middlewareLink.concat(httpLink);
const client = new ApolloClient({ link: link, cache: new InMemoryCache() });
this is what I do. the user is authorized and I save the token to localStorage which I fetch to set on the headers