Search code examples
vue.jsasync-awaitgraphqlvuexapollo-client

Passing Getter to Vuex Action returns null


I'm trying to pass a getter to my async action and it console logs just fine, but the await that calls an apollo mutation keeps seeing it as a null value whereas it just printed a real value to the console... I'm also using vuex-persisted-state to keep the store data alive. So the cartId state is not null by the time the action is performed... hence why it console logs the cartId value correctly.

state:

  cartId: null, //initially null, is set with mounted in another component

getters:

  getCartId(state) {
    return state.cartId
  },

actions:

  async getCartItems({ commit, getters }) {
    let getCartId = getters.getCartId
    console.log(getCartId) // returns: Z2lkOi8vc2hvcGlmeS9DYXJ0LzBhMDIxNDQ2ODQ0ZDU1MGRhZmZmMWJjZTIzNTBhNDY4
    const { data } = await this.app.apolloProvider.defaultClient.query({
      query: getCart,
      variables() {
        return {
          cartId: getCartId
        }
      },
      skip() {
        return !getCartId
      }
    })
  },

Console Error: Uncaught (in promise) Error: GraphQL error: Variable $cartId of type ID! was provided invalid value

GraphQL Response: Expected value to not be null

EDIT: The problem seems to lie with how variables are passes to my query


Solution

  • Fixed by making variables not a function in my await...

    async getCartItems({ commit, getters }) {
        const getCartId = await getters.getCartId
        const { data } = await this.app.apolloProvider.defaultClient.query({
          query: getCart,
          variables: {
            cartId: getCartId
          },
          skip() {
            return !getCartId
          }
        })
        if (data.cart) {
          commit('updateCartObj', data.cart)
        } else {
          console.log('getCartItems Error' + data)
        }
      },