GraphQL post request in axios

ghz 6months ago ⋅ 50 views

I have a problem with GraphQL. I want to send axios.post request to my server. I can do it in postman:

{
    "query":"mutation{updateUserCity(userID: 2, city:\"test\"){id name age city knowledge{language frameworks}}} "
}

and in graphiql:

mutation {
  updateUserCity(userID: 2, city: "test") {
    id
    name
    age
    city
    knowledge {
      language
      frameworks
    }
  }
}

but can't do it in my code:(( here is my code snippet:

const data = await axios.post(API_URL, {
  query: mutation updateUserCity(${ id }: Int!, ${ city }: String!) {
    updateUserCity(userID: ${ id }, city: ${ city }){
      id
      name
      age
      city
      knowledge{
        language
        frameworks
      }
    }
  }
}, {
    headers: {
      'Content-Type': 'application/json'
    }
  })

what's wrong in my code?

Answers

The issue in your code is with the way the query string is constructed. In JavaScript, when creating a GraphQL query or mutation, you need to format it as a proper string, typically using template literals. Additionally, you should not use ${} syntax inside the GraphQL query directly but should use it to interpolate variables correctly into the string.

Here's how you can fix your code:

  1. Use backticks (``) to create a template literal for the GraphQL mutation.
  2. Properly interpolate the id and city variables into the mutation string.

Here's the corrected code snippet:

const id = 2; // Example id
const city = 'test'; // Example city

const mutation = `
  mutation {
    updateUserCity(userID: ${id}, city: "${city}") {
      id
      name
      age
      city
      knowledge {
        language
        frameworks
      }
    }
  }
`;

const data = await axios.post(API_URL, {
  query: mutation
}, {
  headers: {
    'Content-Type': 'application/json'
  }
});

In this code:

  • The mutation string is properly formatted using template literals.
  • The id and city variables are correctly interpolated into the mutation string.

This should work correctly with your GraphQL server.