微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何从 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 举报,一经查实,本站将立刻删除。