Skip to content

Instantly share code, notes, and snippets.

@yusinto
Last active June 3, 2024 15:05
Show Gist options
  • Save yusinto/30bba51b6f903c1b67e0383f4a288269 to your computer and use it in GitHub Desktop.
Save yusinto/30bba51b6f903c1b67e0383f4a288269 to your computer and use it in GitHub Desktop.
Graphql mutation with fetch
const updateCountryFetch = async (countryId, happinessFactor, population) => {
const query = JSON.stringify({
query: `mutation {
updateCountry(
id: "${countryId}"
happinessFactor: ${happinessFactor}
population: ${population}) { id }
}
`
});
const response = await fetch(graphCoolEndpoint, {
headers: {'content-type': 'application/json'},
method: 'POST',
body: query,
});
const responseJson = await response.json();
return responseJson.data;
};
@mailyokesh
Copy link

could you post an example of how to form this mutation with variables? so it can be used using fetch as well?

@christopheragnus
Copy link

christopheragnus commented Aug 6, 2019

@mailyokesh The above example is using Template literals. To pass a variable from an argument, you just use String Interpolation. Eg. see id: "${countryId}".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

@bofcarbon1
Copy link

message: "Must provide query string."}
is what I keep getting and I'm pretty fed up with graphQL at this point.

@phattranky
Copy link

Here is working for me

async function generateConversationWith(userId: string) {
    const response = await fetch(`${process.env.API_URL}/graphql`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: `
          mutation GenerateChatConversationWith {
            generateChatConversationWith(chatWithUserId: "${userId}") {
              id
            }
          }`,
      }),
    });
    const responseData = await response.json();

    console.log("response", responseData);
  }

@ihoskovecpetr
Copy link

Thanks @phattranky 🤝

@longnguyendev
Copy link

thanks @phattranky

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment