Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo Client: Variable is not defined. Received status code 400

I'm trying to use dynamic variable in a GraphQL query using Apollo Client. I have followed the documentation, but Apollo keeps giving me errors, saying that my variables are not defined, and ultimately responding with status code 400.

Here is what the documentation for Apollo said:

mutate: (options?: MutationOptions) => Promise A function to trigger a mutation from your UI. You can optionally pass variables, optimisticResponse, refetchQueries, and update in as options, which will override any props passed to the Mutation component. The function returns a promise that fulfills with your mutation result.

And here is the code I tried to write:

const fetch = require('node-fetch');
const ApolloClient = require('apollo-boost').default;
const gql = require('graphql-tag');

const client = new ApolloClient({
    uri: "http://api.domain.com/graphql",
    fetch
});

run();

async function run() {
    try {
        const resp = await client.mutate({
            mutation: gql`mutation {
                trackPr(id: $id, pr: $pr, title: $title, body: $body, state: $state, merged: $merged) {
                    id
                }
            }`,
            variables: {
                id: 1,
                pr: 1,
                title: "test title",
                body: "test body",
                state: "test state",
                merged: false
            },
        });


        console.log(resp.data);
    } catch(ex) {
        console.log(ex);
    }
}

I'll then get a error message for each variable saying it has not been defined:

[GraphQL error]: Message: Variable "$id" is not defined., Location: [object Object],[object Object], Path: undefined

After each of these error messages, I then get a final message with status code 400:

[Network error]: ServerError: Response not successful: Received status code 400

The mutation itself runs fine without the variables and all the values set directly in the mutation, but I don't know why it thinks the variables are not defined.

like image 549
JSmith Avatar asked Jan 23 '19 14:01

JSmith


1 Answers

Any variables used inside an operation must be declared as part of the operation definition, like this:

mutation SomeOptionalMutationName ($id: ID!) {
  trackPr(id: $id) {
    id
  }
}

This allows GraphQL to validate your variables against the provided type, and also validate that the variables are being used in place of the right inputs.

like image 127
Daniel Rearden Avatar answered Oct 23 '22 08:10

Daniel Rearden