I am trying to access a react context values within the setContext function for my Apollo client. I would like to be able to dynamically update the header for each graphql request with the react context value. But I face an error with no visible error messages in the logs. Is what I am trying to do possible?
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"));
You can use useImperativeHandle to access the context values from outside React tree In the context file create a ref
export const ContextRef = React.createRef();
Then inside the Context add
React.useImperativeHandle(ContextRef, () => contextValues);
Finally, you can access the context values with
ContextRef.current.token
See: https://reactjs.org/docs/hooks-reference.html#useimperativehandle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With