apollographql / apollo-link-state

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

Using @Client with remote data not fetching from persisted cache #309

Closed marvinkome closed 6 years ago

marvinkome commented 6 years ago

When using @client with remote other fields, fetchPolicy: 'cache-and-network doesn't work. Rather it tries to fetch from the network only and throws an error if the network can't be reached. Is there a way to make it hit the cache first before going to the network when the @client is added to a subfield?

Here's my query

query GroupMessages($id: String!) {
        user {
            id
            username
            group(groupId: $id) {
                id
                name
                messages(sort: true, first: 15) @connection(key: "messages") {
                    id
                    message
                    timestamp
                    from {
                        id
                        username
                    }
                    hasError @client
                }
                role {
                    name
                }
            }
        }
    }

Here's my state link

import gql from 'graphql-tag';
import { withClientState } from 'apollo-link-state';

const resolvers = {
    Message: {
        hasError: () => false
    },
    Mutation: {
        addErrorToMessage(_: any, variables: any, { cache, getCacheKey }: any) {
            const id = getCacheKey({
                __typename: 'Message',
                id: variables.id
            });

            const fragment = gql`
                fragment errorMessage on Messages {
                    hasError
                }
            `;

            const message = cache.readFragment({ fragment, id });
            const data = { ...message, hasError: true };

            console.log('writing local cache');
            cache.writeData({ id, data });
            return null;
        }
    }
};

export default (cache: any) =>
    withClientState({
        resolvers,
        cache,
        defaults: {
            Message: {
                __typename: 'Message',
                hasError: false
            }
        }
    });
ghost commented 6 years ago

@marvinkome: How did you solve this problem?

marvinkome commented 6 years ago

I didn't solve it, unfortunately. Did a hack, I just set the id to a negative value if it has an error.