I want to pass a token stored in redux to the ApolloBoost Cliet. How do you acheive this using redux-react-hook library??
import ApolloBoost from 'apollo-boost'
const client = new ApolloBoost({
uri: 'https://api.github.com/graphql',
request: (operation) =>{
operation.setContext({
headers:{
Authorization: `bearer ${token}`
}
})
}
});
export default client
Edit: Tried below but failed
import {useCallback} from 'react'
import ApolloBoost from 'apollo-boost'
import {useMappedState} from 'redux-react-hook'
const client = new ApolloBoost({
uri: 'https://api.github.com/graphql',
request: (operation) =>{
const mapState = useCallback(state => state.token, [])
const token = useMappedState(mapState)
console.log(token)
operation.setContext({
headers:{
Authorization: `bearer ${token} `
}
})
}
});
export default client
Below did the trick. Instead of having a separate file for the client, I integrated the code into App.js, then I was able to pass the token via redux.
import React, {useCallback} from 'react'
import {ApolloProvider} from "react-apollo"
import ApolloBoost from 'apollo-boost'
import {BrowserRouter, Route, Switch, Link} from 'react-router-dom'
import {useMappedState} from 'redux-react-hook'
import SampleComponent from './components/SampleComponent'
import StarredRepos from './components/StarredRepos'
import TokenSession from './components/TokenSession'
export default function App(){
const mapState = useCallback(state => state.token, [])
const token = useMappedState(mapState)
const client = new ApolloBoost({
uri: 'https://api.github.com/graphql',
request: (operation) =>{
console.log(token)
operation.setContext({
headers:{
Authorization: `bearer ${token} `
}
})
}
});
return (
<ApolloProvider client={client}>
<BrowserRouter>
<div className="App">
<div><Link to = {'/SampleComponent'}>SampleComponent</Link></div>
<div><Link to = {'/StarredRepos'}>StarredRepos</Link></div>
<div><Link to = {'/TokenSession'}>TokenSession</Link></div>
<Switch>
<Route path='/sampleComponent' component={SampleComponent}/>
<Route path='/StarredRepos' component={StarredRepos}/>
<Route path='/TokenSession' component={TokenSession}/>
</Switch>
</div>
</BrowserRouter>
</ApolloProvider>
);
}