如何从Redux将值传递给AppolloBoost客户端?

时间:2019-04-21 21:53:45

标签: redux apollo-boost

我想将存储在redux中的令牌传递给ApolloBoost Cliet。您如何使用redux-react-hook库来实现这一目标?

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

编辑:在下面尝试过但失败了

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

1 个答案:

答案 0 :(得分:0)

以下是技巧。我没有为客户端提供单独的文件,而是将代码集成到App.js中,然后能够通过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>
    );
}