react native - Apollo Client Delaying the Authorization Header -


i using apollo (with graph cool), redux, , auth0 in react-native app. trying delay queries , mutations until header set.

the idtoken stored in async storage, , therefore promise. can't use redux pass token, because create circular dependency.

when user logins in first time or token has expired, queries sent before header set, means error error: graphql error: insufficient permissionsenter image description here

how can delay queries until token found , added header? have been searching 3 main solutions:

  1. add forcefetch: true; seems part of earlier implementation of apollo client. if find equivalent, app still fails on first attempt fetch.
  2. reset store (rehydrate?) upon logging in. still asynchronous don't see how affect outcome.
  3. remove mutations , queries login itself, due progress of app, not feasible.

some snippets:

const token = asyncstorage.getitem('token'); const networkinterface = createnetworkinterface({ uri:xxxx})  //adds token in header networkinterface.use([{     applymiddleware(req, next) {         if(!req.options.headers) {             req.options.headers = {}         }         if(token) {             token                 .then(mytoken => {                     req.options.headers.authorization = `bearer ${mytoken}`;                 })                 .catch(err => console.log(err));            }         next(); // middleware needs allow endpoint functions run;     }, }]);  // create apollo client; const client = new apolloclient({     networkinterface,     dataidfromobject: o => o.id }); 

and

const store = createstore(   combinereducers({     token: tokenreducer,     profile: profilereducer,     path: pathreducer,     apollo: client.reducer(),   }),   {}, // initial state   compose(       applymiddleware(thunk, client.middleware(), logger),   ) ); 

i'm not work without reproduction app, because don't have app of structure set up, you're hitting race condition because calling next() outside of async chain.

calling next() tell client continue on request, if token isn't set. instead, let's wait until token comes , header gets set before continuing on.

networkinterface.use([{   applymiddleware(req, next) {     if(!req.options.headers) {       req.options.headers = {}     }     asyncstorage.getitem('token')       .then(mytoken => {          req.options.headers.authorization = `bearer ${mytoken}`;       })       .then(next)  // call next() after authorization header set.       .catch(err => console.log(err));      } }]); 

Comments