apollographql / apollo-link-state

✨ Manage your application's state with Apollo!
MIT License
1.4k stars 101 forks source link

Missing field session in {} #334

Closed TacticCoder closed 5 years ago

TacticCoder commented 5 years ago
export const resolvers = {
    Query: {
        session: (_, variables, { cache }) => {
            try {
                const { session } = cache.readQuery({ query });
                return session;
            } catch (ex) {
                const data = {
                    session: {
                        id: 'session',
                        count: 0,
                        __typename: 'session',
                    },
                };
                const theData = cache.writeData({ data });
                return theData;
            }
        },
    },
    Mutation: {
        addCartItem: (_, variables, { cache }) => {
            let finalCount = 0;
            const { session } = cache.readQuery({ query });
            finalCount = session.count;
            const data = {
                session: {
                    id: 'session',
                    count: finalCount + 1,
                    __typename: 'session',
                },
            };
            cache.writeData({ data });
            return data;
        },
    },
};

const query = gql`
  query getSession{
    session @client {
        count       
        __typename 
    }
  }
`;

While executing this query above I get an warning: "Missing field session in {}" Search on stack and slack but now helpful one.

TacticCoder commented 5 years ago

Solve that, for those who may get in to it at the future, I just needed to add defaults to the withClientState() and use the then() promise while loading the cache,

persistCache({
    cache,
    storage: window.localStorage,
    maxSize: false, // set to unlimited (default is 1MB https://github.com/apollographql/apollo-cache-persist)
    debug: true,     // enables console logging
}).then(() => {
    // Continue setting up Apollo as usual.
    ReactDOM.render( ......