1 | ---
|
2 | title: apollo-link-context
|
3 | description: Easily set a context on your operation, which is used by other links further down the chain.
|
4 | ---
|
5 |
|
6 | The `setContext` function takes a function that returns either an object or a promise that returns an object to set the new context of a request.
|
7 |
|
8 | It receives two arguments: the GraphQL request being executed, and the previous context. This link makes it easy to perform async look up of things like authentication tokens and more!
|
9 |
|
10 | ```js
|
11 | import { setContext } from "apollo-link-context";
|
12 |
|
13 | const setAuthorizationLink = setContext((request, previousContext) => ({
|
14 | headers: {authorization: "1234"}
|
15 | }));
|
16 |
|
17 | const asyncAuthLink = setContext(
|
18 | request =>
|
19 | new Promise((success, fail) => {
|
20 | // do some async lookup here
|
21 | setTimeout(() => {
|
22 | success({ token: "async found token" });
|
23 | }, 10);
|
24 | })
|
25 | );
|
26 | ```
|
27 |
|
28 | ## Caching lookups
|
29 |
|
30 | 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!
|
31 |
|
32 | Take for example a user auth token being found, cached, then removed on a 401 response:
|
33 |
|
34 | ```js
|
35 | import { setContext } from "apollo-link-context";
|
36 | import { onError } from "apollo-link-error";
|
37 |
|
38 | // cached storage for the user token
|
39 | let token;
|
40 | const withToken = setContext(() => {
|
41 | // if you have a cached value, return it immediately
|
42 | if (token) return { token };
|
43 |
|
44 | return AsyncTokenLookup().then(userToken => {
|
45 | token = userToken;
|
46 | return { token };
|
47 | });
|
48 | });
|
49 |
|
50 | const resetToken = onError(({ networkError }) => {
|
51 | if (networkError && networkError.name ==='ServerError' && networkError.statusCode === 401) {
|
52 | // remove cached token on 401 from the server
|
53 | token = null;
|
54 | }
|
55 | });
|
56 |
|
57 | const authFlowLink = withToken.concat(resetToken);
|
58 | ```
|