Update ApolloClient Headers After It Was Initialised
My app is wrapped with <Apollo />
component that essentially initialises the client.
const client = new ApolloClient({
link: new HttpLink({
// ...
}),
cache: new InMemoryCache({
// ..
}),
});
Further down the road users can make certain action that requires me to set few new headers to apollo client that were not there before. I initially thought to use react context for this to pass set new headers and consume them inside <Apollo />
but am not sure if this is the right way to go about it.
After looking through the docs, it seems that apollo headers can be only set when it is initialised?
Answer
Rather than passing the headers directly to your Apollo client instance, you normally want to utilize apollo-link-context
. You can store the actual header values in memory, LocalStorage or whatever makes sense for your app. Then use the link to inject them into each request before it's sent:
const headerLink = setContext((request, previousContext) => ({
headers: {
// Make sure you include any existing headers!
...previousContext.headers,
authorization: localStorage.getItem('authHeader')
},
}));
const client = new ApolloClient({
link: headerLink.concat(httpLink),
cache: new InMemoryCache()
});
setContext
can be asynchronous. The function you pass it should return either an object with whatever context fields you want to change, or a Promise that will resolve to one:
const headerLink = setContext(async (request, previousContext) => {
const authorization = await someAsyncCall()
return {
headers: {
...previousContext.headers,
authorization,
},
}
});
You can check out the docs for additional examples.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?