Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Apollo GraphQL : Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag?

I keep getting this error when trying to update cache after mutation:

Possible Unhandled Promise Rejection (id: 0): Invariant Violation: Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag?

The mutation succeeds, then I run this code inside the onCompleted method.

const cards = this.props.client.readQuery({ FETCH_CARDS, variables: { userId: data.createPaymentMethod.userId } });

const { id,
        brand,
        lastFour,
        userId,
        stripeID } = data.createPaymentMethod

const paymentMethod = {
  id: id,
  brand: brand,
  lastFour: lastFour,
  userId: userId,
  stripeID: stripeID,
  __typename: 'PaymentMethod',
};

// Write back to the to-do list and include the new item
this.props.client.writeQuery({
  FETCH_CARDS,
  data: {
    paymentMethod: [...cards.paymentMethod, paymentMethod],
  },
});

I don't understand what I'm doing wrong. I'm following this guide: https://www.apollographql.com/docs/react/caching/cache-interaction/#writequery-and-writefragment

EDIT: FETCH_CARDS

const FETCH_CARDS = gql`
  query PaymentMethod($userId: ID){
    paymentMethod(userId: $userId) {
      id
      brand
      lastFour
      userId
      stripeID
    }
  }
`;
like image 527
Hugo Avatar asked Oct 22 '19 11:10

Hugo


2 Answers

For me, the solution was changing readQuery({ FETCH_CARDS to readQuery({ query: FETCH_CARDS and the same for writeQuery(). I agree that their example appears misleading, because they name their gql call "query" instead of a normal all-caps name. But really it's to tee up shorthand object prop notation for readQuery({ query: query.

like image 54
Teagan Atwater Avatar answered Nov 11 '22 14:11

Teagan Atwater


When this happens to me, the issue is usually as simple as the import for FETCH_CARDS not resolving correctly. It is hard to determine without having the complete example, I'd need to be able to see the entire file for each of the code samples and the directory structure.

like image 36
matsilva Avatar answered Nov 11 '22 15:11

matsilva