VikR
VikR

Reputation: 5142

Apollo/GraphQL Mutation Works in GraphIQL, but Not in Client Code?

I have this mutation working correctly in GraphIQL at http://localhost:8080/graphiql:

QUERY

mutation($fromID: String!, $toID: String!, $msgText: String!){
  createIM(fromID: $fromID, toID: $toID, msgText: $msgText){
    fromID
    toID
    msgText
  }
}

...AND QUERY VARIABLES

{
  "fromID": "1",
  "toID": "2",
  "msgText": "Test from GraphIQL #3. It's working!!!"
}

Now I need to implement this in code.

CLIENT CODE

sendInstantMsg(){
    const {textToSend} = this.refs;
    const {toID} = this.props;

    const fromID = Meteor.userId();
    const msgText = trimInput(textToSend.getValue());

    client.query({
        query: gql`
            query mutation($fromID: String!, $toID: String!, $msgText: String!){
                createIM(fromID: $fromID, toID: $toID, msgText: $msgText){
                    fromID
                    toID
                    msgText
                }
            }
        `,
        variables: {
            fromID: fromID,
            toID: toID,
            msgText: msgText
        },
        forceFetch: false,
    }).then(({ data }) => {
        console.log('got data', data);
    }).catch((error) => {
        console.log('there was an error sending the query', error);
    });
}

The query variables (fromID, toID, and msgText) come in to the function as expected, but Apollo throws an error:

message: "Network error: Unexpected token < in JSON at position 0"

What am I missing?

Upvotes: 1

Views: 1142

Answers (1)

HagaiCo
HagaiCo

Reputation: 706

Please try this instead.. you should use mutate for mutations not query..

client.mutate({
            mutation: gql`
                mutation createIM($fromID: String!, $toID: String!, $msgText: String!){
                    createIM(fromID: $fromID, toID: $toID, msgText: $msgText){
                        fromID
                        toID
                        msgText
                    }
                }
            `,
            variables: {
                fromID: fromID,
                toID: toID,
                msgText: msgText
            },
            forceFetch: false,
        }).then(({ data }) => {

Upvotes: 2

Related Questions