I am hitting an api and saving response in a variable but the variable in which i am storing is showing undefined by debugger.
try {
let response = await fetch(
"http://test.kelltontech.net/eventengine/getmyevents?hash=****×tamp=****&id=****",
{
method: "GET",
headers: {
"Content-Type": "application/json"
}
}
);
let responseJson = await response.json();
this.agendaDetails = await responseJson;
} catch (error) {
alert(error);
}
Here responseJson has data but not storing in agenda detail that is declared outside the main class like this agendaDetails={}
As an aside, and perhaps a better long term solution; instead of using fetch and wrapping it in a promise and making a tweak to return json. Use axios. It has promise support as standard and returns and expects json output.
let result = {};
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
result = response.data;
})
.catch(function (error) {
console.log(error);
});
Here is the link axios
you should use fetch with .then() to get response in json then assign that response to the variable just like below
fetch(URL.apiUrlUploadImages, {
method: "POST",
headers: {
Accept: 'application/json',
'Authorization': 'Bearer ' + this.token,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"front_image": this.frontImageData
})
})
.then((response) => response.json())
.then((responseData) => {
var result = responseData});
Related
So I am making a request to an API endpoint. When I print JSONBody which is the variable data passed to POSTRequest(), I get the JSON I created printed to the log, however when I then try and JSON.Stringify() it, I get returned an empty object?
Was just wondering what I am doing wrong and how to fix it :)
getFileData()
const getFileData = () => {
var data = {}
// DO SOME STUFF HERE TO data
POSTRequest(data);
}
POSTRequest()
const POSTRequest = async (JSONBody) => {
console.log(JSONBody)
console.log(JSON.stringify(JSONBody))
try {
const response = await fetch(API_ENDPOINT, {
method: 'POST',
body: JSON.stringify(JSONBody),
headers: { 'Content-Type': 'application/json' }
});
response.json()
.then(function (res) {
Promise.resolve(res)
.then(function (finalData) {
console.log(finalData);
props.setData(finalData);
});
});
} catch (error) {
console.log(error);
}
}
You're not waiting for the response from the fetch call correctly, try this:
const POSTRequest = async (JSONBody) => {
console.log(JSONBody)
console.log(JSON.stringify(JSONBody))
await fetch(API_ENDPOINT, {
method: 'POST',
body: JSON.stringify(JSONBody),
headers: { 'Content-Type': 'application/json' }
}).then((response) => {
console.log(response);
props.setData(response);
}).catch((error) => {
console.log('POSTRequest error: ' + error)
})
});
I have this function in my context provider I want it to return a promise so that I can access the returned data from axios
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
},
data: data
};
axios(config)
.then(function (res) {
return res
})
.catch(function (error) {
return error
});
}
And the result I'm looking for is to write such code in every other component whenever I needed
sendRquest('usermanagement',data,'post','foo/bar').then(res=>console.log(res.data)).catch(err=>console.log(err))
You have to return the promise.
Something like
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
},
data: data
};
return axios(config)
.then(function (res) {
return res
})
.catch(function (error) {
return error
});
}
Be careful tho because you are "swallowing" errors by using .catch like this. The promise returned by sendRquest will never "fail" (reject) but will succeed (resolve) with either data or error payloads.
the complete answer is like this
may help you all
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
'Authorization': token
},
data: data
};
return axios(config)
}
I'm trying to consolidate some code in one of my react components because my componentDidMount method is getting a bit verbose. This gave me the idea to create an api that does all of my data fetching for the entire app.
I'm having an asynchronous issue I'm not sure how to resolve.
I created the separate api file (blurt.js):
exports.getBlurts = function() {
var blurtData = null;
fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((data) => {
blurtData = data;
});
return blurtData;
}
and imported it to my (.jsx) component via
import blurtapi from '../api/blurt.js';
The problem is that when I call blurtapi.getBlurts() within componentDidMount(), the value comes back as null. However, if I write the data to the console like so:
.then((data) => {
console.log(data);
});
all is as it should be. So, the function is returning before the db operation completes, hence the null value. How would I reign in the asynchronous aspect in this case? I tried an async.series([]) and didn't get anywhere.
Thanks
So fetch returns a promise, which it is async , so any async code will run after sync code. so this is the reason you get null at first.
However by returning the async function , you are returning a promise.
Hence this code:
exports.getBlurts = async () => {
const data = await fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
const jsonData = await data.json();
return jsonData;
}
To retrieve any promise data, you need the then function,
so in your componentDidMount, you will do:
componentDidMoint() {
blurtapi.getBlurts()
.then(data => console.log(data)) // data from promise
}
Promises:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
async/await:
https://javascript.info/async-await
I hope this makes sense.
fetch call returns a promise. therefore in your function u do something like this
exports.getBlurts = function() {
var blurtData = null;
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
}
And do this in your componentDidMount
componentDidMount(){
blurtapi.getBlurts().then((data)=>{
this.setState({data})
}
}
In your example return blurtData; line will run synchronously, before the promise is resolved.
Modify getBlurts as:
exports.getBlurts = function() {
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((data) => {
return data;
});
}
And in componentDidMount:
componentDidMount() {
getBlurts.then((data) => {
// data should have value here
});
}
exports.getBlurts = function() {
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(res => return res)
async componentDidMount() {
const response = await blurtapi.getBlurts();
}
or
exports.getBlurts = function() {
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
componentDidMount() {
const data = blurtapi.getBlurts()
.then(data => {
// Do something or return it
return data;
});
}
I am using Fetch-node for a GET to a service.
const response = await fetch("MY URL", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
timeout: 5000,
}).then(res => res.json()).then(json => console.log(json));
console.log(response);
I log the result in the second console.log() then and everything is fine.
However, when it comes to the second console.log() the response is undefined.
What I need is whatever is logged in the second to be stored in the response.
Is there anything wrong with what I am doing?
As mentioned, you're not returning a value for response, therefore it won't be equal to anything. You could return the JSON from your final then, or if you felt it was any cleaner, just await both instead of using .then at all.
const response = await fetch("MY URL", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
timeout: 5000
});
const json = await response.json();
console.log(json);
You should return your value in your function.
const response = await fetch("MY URL", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
timeout: 5000,
}).then(res => res.json()).then(json => {
// do something
return json //<--- return a value
});
console.log(response);
You can write the whole code with async/await. In your code you mixed promise and async/await syntax, and forgot to return json from last .then() function.
This is how I write the code:
async function fetchData() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
timeout: 5000,
})
const data = await response.json();
console.log(data);
}
fetchData();
I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.
Code:
componentDidMount() {
Linking.getInitialURL().then(url => {
if(url) {
console.log(url);
const queries = url.substring(16)
const dataurl = qs.parse(queries);
if(dataurl.state === 'ungessable15156145640!') {
console.log(dataurl.code);
console.log(dataurl.state);
return code = dataurl.code;
}
}
}).then((code) => {
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
var access_token = res;
console.log(access_token);
});
});
}
You almost got it right, you are missing one step though!
fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json); // The json object is here
});
It's a good practice to add a catch just in case something goes wrong.
.then((json) => {
console.log(json); // The json object is here
});
.catch((err) => {
// Handle your error here.
})