apollo-feature-requests icon indicating copy to clipboard operation
apollo-feature-requests copied to clipboard

addTypePolicies does not work as expected for local fields

Open sirugh opened this issue 3 years ago • 10 comments

Intended outcome:

Type Policies for local state fields added through addTypePolicies at render/mount of component should allow for querying of those fields from that point on.

Actual outcome:

Type Policies for local state fields added through addTypePolicies at render/mount of component return undefined data and no errors. loading state indicates that the query executed.

Note: I dug into the addTypePolicies call and for both scenarios it seems like the type is added. The image shows the same resulting state for adding policy via initialization or adding policy via component calling addTypePolicies.

How to reproduce the issue:

See sandbox: https://codesandbox.io/s/local-query-typepolicies-bug-s2ssq?file=/src/index.js

Instructions within, but at a high level - it seems to be the difference between applying type policies to the cache at creation vs applying type policies at a later time. I have tried to narrow down the sandbox as much as I could.

// This works and `message` is queryable.
const cache = new InMemoryCache({
    typePolicies: {
        Query: {
            fields: {
                message: {
                    read() {
                        return 'Hello World';
                    }
                }
            }
        }
    }
});

vs

// This doesn't work and `message` returns undefined.
const MyComponent = () => {
  const apolloClient = useApolloClient();
  useEffect(() => {
    apolloClient.cache.policies.addTypePolicies({
        Query: {
            fields: {
                message: {
                    read() {
                        return 'Hello World';
                    }
                }
            }
        }
    });
  }, [apolloClient, typePolicies]);
}

Versions Image from Gyazo

sirugh avatar Mar 25 '21 17:03 sirugh