question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[question] Is there a way to access the redux store in useAfter

See original GitHub issue

Hey everyone. I am trying to use the middleware and afterware of the apollo-client. Is there any way to access the redux store at this point?

Problem:

At the middleware i am attaching my auth-token to every request like:

networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    // get the authentication token from local storage if it exists
    const token = localStorage.getItem('token');
    // here i would like to read the token from the store instead of the localStorage
    req.options.headers.authorization = token ? token : null;
    next();
  }
}]);

If my server returns an 401 status code i would like to send an logout action to my redux store at the userAfter.

networkInterface.useAfter([{
  applyAfterware({ response }, next) {
    if (response.status === 401) {
      localStorage.setItem('token', '')
      // here i would like to dispatch an redux action
      // e.g. dispatch({ type: 'LOGOUT' })
    }
    next();
  }
}]);

But the store is declared after the NetworkInterface because it needs the client at creation time.

const client = new ApolloClient({
  networkInterface
});

const initialState = {};

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
  combineReducers({
    ...reducers,
    apollo: client.reducer(),
  }),
  initialState,
  compose(
    applyMiddleware(client.middleware()),
    applyMiddleware(sagaMiddleware),
    (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined') ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
  )
);

If you need some more information please ask me or take a look at the project files: https://github.com/cpotemski/aquata/blob/96d53d082e62c9db7f28a36335ee9ce2e36e720e/client/src/index.js#L36

Version

  • apollo-client@1.4.2

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
cpotemskicommented, Nov 6, 2017

I am declaring an empty variable for the store and use this variable in my afterware…

let store

networkInterface.useAfter([{
  applyAfterware({ response }, next) {
    if (response.status === 401) {
      localStorage.setItem('token', '')
      store.dispatch(logout())
    }
    next();
  }
}]);

… and fill it afterwards

store = createStore(
  combineReducers({
    ...reducers,
    apollo: client.reducer(),
  }),
  initialState,
  compose(
    applyMiddleware(client.middleware()),
    applyMiddleware(sagaMiddleware),
    (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined') ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
  )
);

So this works fine, because the first network-request ist after the initialization. It’s not the best way, but a good workaround.

Complete code: https://github.com/cpotemski/aquata/blob/4a87f50882af6a9ee9fb2380a268c3e947a7a957/client/src/index.js

I hope that helps 😉

0reactions
cpotemskicommented, Nov 7, 2017

@UncleJimmy Yeah I just upgraded to apollo-client 2.0.0 yesterday and saw they removed redux from apollo. So now I use both in parallel. I will try to remove redux if possible because I only use some redux features. It was a little bit difficult but it works now.

I solved the concat issue this way

const link = middlewareLink.concat(errorLink.concat(httpLink))

but i think the better way would be

const link = ApolloLink.concat(
  middlewareLink,
  errorLink,
  httpLink
)

Here is my current code: https://github.com/cpotemski/aquata/blob/fb1ce5821d9f59eac6a237936c06a775a3b34605/client/src/index.js

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is the best way to access redux store outside a react ...
Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute...
Read more >
Access the Redux Store Outside a React Component
In the examples below I'll show how to access a JWT token from the Redux store, but the techniques will work with any...
Read more >
Redux Fundamentals, Part 4: Store
The official Redux Fundamentals tutorial: learn how to create and use a Redux store.
Read more >
Redux Fundamentals, Part 5: UI and React
The official Redux Fundamentals tutorial: learn how to use Redux with React.
Read more >
What is the proper way to access Redux store? - JS IQ
The best way to access your store in a component is to use the connect() function, that creates a new component that wraps...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found