Skip to content

Commit

Permalink
Avoid storing Symbol property on React object in ApolloContext.ts.
Browse files Browse the repository at this point in the history
Fixes the Symbol-related errors reported in #7370.
  • Loading branch information
benjamn committed Nov 24, 2020
1 parent 635b844 commit c46e02f
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions src/react/context/ApolloContext.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import * as React from 'react';
import { ApolloClient } from '../../core';
import { canUseWeakMap } from '../../utilities';

export interface ApolloContextValue {
client?: ApolloClient<object>;
Expand All @@ -10,27 +11,21 @@ export interface ApolloContextValue {
// (which can lead to problems like having an Apollo Client instance added
// in one context, then attempting to retrieve it from another different
// context), a single Apollo context is created and tracked in global state.
// Since the created context is React specific, we've decided to attach it to
// the `React` object for sharing.
// We use React.createContext as the key instead of just React to avoid
// ambiguities between default and namespace React imports.

// If Symbol's aren't available, we'll use a fallback string as the context
// property (we're looking at you, IE11).
const contextSymbol = typeof Symbol === 'function' && Symbol.for ?
Symbol.for('__APOLLO_CONTEXT__') :
'__APOLLO_CONTEXT__';

export function resetApolloContext() {
Object.defineProperty(React, contextSymbol, {
value: React.createContext<ApolloContextValue>({}),
enumerable: false,
configurable: true,
writable: false,
});
}
const cache = new (canUseWeakMap ? WeakMap : Map)<
typeof React.createContext,
React.Context<ApolloContextValue>
>();

export function getApolloContext() {
if (!(React as any)[contextSymbol]) {
resetApolloContext();
let context = cache.get(React.createContext)!;
if (!context) {
context = React.createContext<ApolloContextValue>({});
cache.set(React.createContext, context);
}
return (React as any)[contextSymbol] as React.Context<ApolloContextValue>;
return context;
}

export { getApolloContext as resetApolloContext }

0 comments on commit c46e02f

Please sign in to comment.