GraphQL returns null on mutation [duplicate] - javascript

This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
I'm using GraphQL to connect to multiple RESTful endpoints. I'm writing a mutation to update user details, however GraphiQL is showing the following response of null rather than the updated user ID and name...
{
"data": {
"updateUser": null
}
}
updateUser: (parent, args) => {
const { id, name } = args;
return fetch(`${url}/users/${id}`, {
method: 'PUT',
body: JSON.stringify({ id, name }),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
},
Thanks in advance.

You need to return your resolved json, otherwhise there is no returning value for the fetch call.
.then(json => json);
or if you want
.then(json => {
console.log(json);
return json;
});

Related

How to get fetch response and then anssing the response to var in Javascript? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am trying to do a GET request with vanilla javascript from a .html, and I am looking to assign the response inside a variable, I have to use the response to manipulate the DOM however, I get a Promise < pending > and not a JSON
This is my code:
let data = fetch('http://localhost/api/products')
.then(response => response.json())
console.log(data)
I'd like to get this from console.log(data):
{ "name": "SHOES", "price": 129}
this code will be a good guide, you can get json data at then second then
const getCart = () => {
fetch("/cart.js", {
method: 'GET',
headers: new Headers({'content-type': 'application/json', 'X-Requested-With':'xmlhttprequest'})
}).then(res => {
return res.json();
}).then(json => {
console.log(json);
});
}

add parameters to a post request in js [duplicate]

This question already has answers here:
How can I pass POST parameters in fetch request? - React Native
(2 answers)
Closed 1 year ago.
I need to add some parameters to this request:
fetch(url_ticket, {
//body: JSON.stringify(data),
//mode: 'no-cors',
param: {
'token': `${token}`,
'id': `${id}`,
'id_secret': `${id_secret}`
},
method: 'POST'
})
.then(response => {
console.log(response.text());
})
.catch(error => {
console.error(error);
});
However, I'm getting an error. I've made that request in Postman an it works, so the problem is obviously in this code. I think the error is in the params parameter; how can I add properly parameters in this request?
I'm literally new to js, i've searched for answers but i can't understand a thing, so posting my real problem has been my last option
Here is the code to send post request with parameter
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
For info you can read doc here Using fetch
I think this SO answer is a nice and clean way to do it. Basically, it constructs the URL string with parameters.
fetch(url_ticket + new URLSearchParams({
token: `${token}`,
id: `${id}`,
id_secret: `${id_secret}`
}), {});
You could also construct the parameters in a more manual way, by inserting the variables into a backticked URL string:
let url = `${url_ticket}?token=${token}&id=${id}&id_secret=${id_secret}`;
fetch(url, {...})

fetch().then() return content-type and body [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 4 years ago.
Every fetch API example on the internet shows how to return only the body using response.json(), response.blob() etc.
What I need is to call a function with both the content-type and the body as a blob and I cannot figure out how to do it.
fetch("url to an image of unknown type")
.then((response) => {
return {
contentType: response.headers.get("Content-Type"),
raw: response.blob()
})
.then((data) => {
imageHandler(data.contentType, data.raw);
});
This obviously doesn't work: data.contentType is filled, but data.raw is a promise. How can I get both values in the same context?
You could write it that way:
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
return {
contentType: response.headers.get("Content-Type"),
raw: blob
}
})
})
.then(data => {
imageHandler(data.contentType, data.raw);
});
Or this way
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
imageHandler(response.headers.get("Content-Type"), blob)
})
})
In both cases you keep the callback in which you receive the resolved blob within the scope where you have access to response.
If you are allowed to use async functions the best solution is to use async/await
async function fetchData() {
const res = await fetch('url');
const contentType = res.headers.get('Content-Type');
const raw = await res.blob();
// you have raw data and content-type
imageHandler(contentType, raw);
}
If not:
fetch('')
.then((res) => res.blob().then((raw) => {
return { contentType: res.headers.get('Content-Type'), raw };
}))
.then((data) => {
imageHandler(data.contentType, data.raw);
});
Wait for the blob then create the object :
fetch("url to an image of unknown type")
.then(response => {
return response.blob()
.then(raw => ({
contentType: response.headers.get("Content-Type"),
raw
}));
).then(data => imageHandler(
data.contentType,
data.raw
));

How to get the JSON from promise [duplicate]

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 4 years ago.
Code:
fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, {
method: "GET",
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => {
console.log(response.json())
})
Output:
Promise {_40: 0, _65: 0, _55: null, _72: null}
Add another then:
fetch(...).then(resp => resp.json()).then(data => ...)
Note that fetch will only error on a network errors, if you want it to reject the Promise on e.g. a 500 response you'll have to check the status code and throw:
fetch(url)
.then(resp => {
// you'll need to supply the function that checks the status here
if (http_response_ok(resp.status)) {
return resp.json();
} else {
throw new Error(`Got back ${resp.status}`);
}
}).then(data => {
// happy path
}).catch(err => {
// sad path
});
You could await the response:
fetch(url, options).then(async (response) => {
const data = await response.json();
console.log(data)
})

Node Fetch Post Request using Graphql Query

I'm trying to make a POST request with a GraphQL query, but it's returning the error Must provide query string, even though my request works in PostMan.
Here is how I have it running in PostMan:
And here is the code I'm running in my application:
const url = `http://localhost:3000/graphql`;
return fetch(url, {
method: 'POST',
Accept: 'api_version=2',
'Content-Type': 'application/graphql',
body: `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
Any ideas what I'm doing wrong? Is it possible to make it so that the body attribute I'm passing in with the fetch request is formatted as Text like I've specified in the PostMan request's body?
The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.
This should work in your case:
const url = `http://localhost:3000/graphql`;
const query = `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
return fetch(url, {
method: 'POST',
Header: {
'Content-Type': 'application/graphql'
}
body: query
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
This is how to submit GraphQL variables:
const query = `
query movies($first: Int!) {
allMovies(first: $first) {
title
}
}
`
const variables = {
first: 3
}
return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
return data
})
.catch((e) => {
console.log(e)
})
I created a complete example on GitHub.

Categories