0

I need to implement a login in react native using apollo, and wanted to know

a) how to replace or remove the middleware in from the client networkinterface. I shouldn't access the _middlewares property directly right? I see a use method which pushes a middlware on, but don't see a way to remove.

b) if we want to change the example from localstorage to asyncstorage, should we instead have the networkinterface read from a redux store directly? What's the best way to do this?

// in src/index.js
const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })

networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}
    }

    // change this from localstorage to asyncstorage, or perhaps redux store
    if (localStorage.getItem('auth0IdToken')) {
      req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
    }
    next()
  },
}])
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

1 Answers1

1

a) At this time (apollo-client@0.6.0) there is no way to remove middleware attached to NetworkInterface.

b) You could use following schema:

// in src/index.js
const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })

// structure of auth reducer:
// auth: {
//   token: "xyz"
// }

//create redux's store before using of middleware
const store: Store<any> = createStore(combineReducers({
  auth = authReducer 
})

networkInterface.use([{
  applyMiddleware (req, next) {
    const tokenFromReduxStore = store.getState().auth.token;

    if (!req.options.headers) {
      req.options.headers = {}
    }

    // change this from localstorage to asyncstorage, or perhaps redux store
    if (tokenFromReduxStore) {
      req.options.headers.authorization = tokenFromReduxStore
    }
    next()
  },
}])