Context Link
Easily set a context on your operation, which is used by other links further down the chain.
Overview
The setContext
function accepts a function that returns either an object or a promise, which then returns an object to set the new context of a request. It receives two arguments: the GraphQL request being executed, and the previous context. This link makes it easy to perform the asynchronous lookup of things like authentication tokens and more.
1import { setContext } from "@apollo/client/link/context";
2
3const setAuthorizationLink = setContext((request, previousContext) => ({
4 headers: {authorization: "1234"}
5}));
6
7const asyncAuthLink = setContext(
8 request =>
9 new Promise((success, fail) => {
10 // do some async lookup here
11 setTimeout(() => {
12 success({ token: "async found token" });
13 }, 10);
14 })
15);
Caching lookups
Typically async actions can be expensive and may not need to be called for every request, especially when a lot of request are happening at once. You can setup your own caching and invalidation outside of the link, to make it faster but still flexible.
Take for example a user auth token being found, cached, then removed on a 401 response:
1import { setContext } from "@apollo/client/link/context";
2import { onError } from "@apollo/client/link/error";
3
4// cached storage for the user token
5let token;
6const withToken = setContext(() => {
7 // if you have a cached value, return it immediately
8 if (token) return { token };
9
10 return AsyncTokenLookup().then(userToken => {
11 token = userToken;
12 return { token };
13 });
14});
15
16const resetToken = onError(({ networkError }) => {
17 if (
18 networkError &&
19 networkError.name ==='ServerError' &&
20 networkError.statusCode === 401
21 ) {
22 // remove cached token on 401 from the server
23 token = null;
24 }
25});
26
27const authFlowLink = withToken.concat(resetToken);