如何从Apollo设置上下文http链接访问反应上下文 [英] How to acess React context from Apollo set Context Http Link

查看:17
本文介绍了如何从Apollo设置上下文http链接访问反应上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问我的Apollo客户端的setContext函数中的Reaction上下文值。我希望能够使用Reaction上下文值动态更新每个GraphQL请求的头。但我遇到一个错误,日志中没有可见的错误消息。我正在尝试做的事情可能吗?

import React, { useState, useContext } from "react";
import { render } from "react-dom";

import ApolloClient from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";

import Select from "./Select";
import CurrencyContext from "./CurrencyContext";
import ExchangeRates from "./ExchangeRates";

const httpLink = createHttpLink({
  uri: "https://48p1r2roz4.sse.codesandbox.io"
});

const authLink = setContext((_, { headers }) => {

  const token = localStorage.getItem("token");


  const currency = useContext(CurrencyContext); // How to access React context here ?


  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
      currencyContext: currency ? currency : {}
    }
  };
});

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

const currencies = ["USD", "EUR", "BTC"];

const App = () => {
  const [currency, setCurrency] = useState("USD");

  return (
    <ApolloProvider client={client}>
      <CurrencyContext.Provider value={currency}>
        <h2>Provide a Query variable from Context 🚀</h2>
        <Select value={currency} setValue={setCurrency} options={currencies} />
        <ExchangeRates />
      </CurrencyContext.Provider>
    </ApolloProvider>
  );
};

render(<App />, document.getElementById("root"));

推荐答案

您可以使用useImperativeHandle从反应树外部访问上下文值 在上下文文件中创建引用

export const ContextRef = React.createRef();

然后在上下文中添加

React.useImperativeHandle(ContextRef, () => contextValues);

最后,您可以使用

访问上下文值
 ContextRef.current.token

参见:https://reactjs.org/docs/hooks-reference.html#useimperativehandle

这篇关于如何从Apollo设置上下文http链接访问反应上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆