3
votes

I have a vue-apollo (using nuxt) query that is supposed to have a local client field show. However, when I have the show @client line included in the query the component does not render. For some reason it also seems to fail silently.

query myAccounts {
  accounts: myAccounts {
    email
    calendars {
      id
      name
      hex_color
      is_enabled
      show @client
    }
  }
}

I am extending the Calendar type in an extensions.js file (pasted below) with two mutations.

import gql from 'graphql-tag'

export const typeDefs = gql`
  extend type Calendar {
    show: Boolean
  }
  type Mutation {
    showCalendar(id: ID!): Boolean
    hideCalendar(id: ID!): Boolean
  }
`

Here is the resolver that sets the value, along with the Apollo config:

import { InMemoryCache } from 'apollo-cache-inmemory'
import { typeDefs } from './extensions'
import MY_ACCOUNTS_QUERY from '~/apollo/queries/MyAccounts'

const cache = new InMemoryCache()

const resolvers = {
  Mutation: {
    showCalendar: (_, { id }, { cache }) => {
      const data = cache.readQuery({ query: MY_ACCOUNTS_QUERY })
      const found = data.accounts
        .flatMap(({ calendars }) => calendars)
        .find(({ id }) => id === '1842')
      if (found) {
        found.show = true
      }
      cache.writeQuery({ query: todoItemsQuery, data })
      return true
    }
  }
}

export default context => {
  return {
    cache,
    typeDefs,
    resolvers,
    httpLinkOptions: {
      credentials: 'same-origin'
    },
  }
}

along with the nuxt config:

apollo: {
  defaultOptions: {
    $query: {
      loadingKey: 'loading',
      fetchPolicy: 'cache-and-network',
    },
  },
  errorHandler: '~/plugins/apollo-error-handler.js',
  clientConfigs: {
    default: '~/apollo/apollo-config.js'
  }
}
1
Please edit the question to include your Apollo client configuration.Daniel Rearden
Added. I'm wondering how it fails if there is no key/value in the cache, as one only gets set if there is a mutation.Zachary Russell Heineman

1 Answers

2
votes

Querying local state requires the state to exist (i.e. it should be initialized) or for a local resolver to be defined for the field. Apollo will run the resolver first, or check the cache directly for the value if a resolver is not defined. There's not really a good way to initialize that value since it's nested inside a remote query, so you can add a resolver:

const resolvers = {
  Calendar: {
    show: (parent) => !!parent.show,
  },
  // the rest of your resolvers
}

See the docs for additional examples and more details.