如何从 React 上下文 API 获取 accessToken 并将其放入 Apollo 的 HttpLink?

问题描述

我有以下项目结构(大致),

src/
  index.tsx -> entry point for React
  App.tsx 
  client.tsx -> Apollo client deFinition
  components/
    TokenProvider.tsx -> Provider for accesstoken

index.tsx 如下所示,它为整个应用程序提供 apollo-clientaccesstoken

import React from "react";
import { render } from "react-dom";

import { ApolloProvider } from "@apollo/client";

import { TokenProvider } from "./components/TokenContext";
import client from "./client";
import App from "./App";

render(
  <ApolloProvider client={client}>
    <TokenProvider>
      <App />
    </TokenProvider>
  </ApolloProvider>,document.getElementById("root")
);

client.tsx 如下所示,

import { ApolloClient,InMemoryCache,HttpLink } from "@apollo/client";

const httpLink = new HttpLink({
  uri: "http://localhost:4000",credentials: "include",});

const client = new ApolloClient({
  cache: new InMemoryCache(),link: httpLink,});

export default client;

我正在尝试执行一些授权操作,因此我需要将 authorization 标头添加HttpLink 中的 client.tsx

所以在 index.tsx 中,我需要类似以下内容

// in index.tsx

const httpLink = new HttpLink({
  uri: "http://localhost:4000",headers: {
    authorization: `bearer ${accesstoken}`,// I need this <---
  },});

问题是,accesstoken 变量可以通过 useContext API 访问,因为它是由 React Context 提供的。但是 client.tsx 不是 React 组件,所以我无法访问它。

如果有可用的刷新令牌,我会在 user login 或应用程序的开头设置 accesstoken。所以在App.tsx中,

// in App.tsx
  useEffect(() => {
    // prevent login in every refresh
    refreshAccesstoken().then((accesstoken) => {
      // dispatch comes from `TokenProvider`
      dispatch({ type: CHANGE_TOKEN,payload: { accesstoken } });
    });
  },[])

有什么办法可以解决这个问题吗?也许我不应该为 Context API 提供 accesstoken,其他的解决方案是什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)