I am trying to get pub locations data from MYSQL server and my fetch function works well. But after that, this try-catch block does not return anything. I also tried without try-catch block but it does not change anything
getPubsFromDatabase = async () => {
let response = await fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
try{
let json = await response.json();
console.log(json)
return json;
}
catch (error) {
console.log(error);
}
}
And here, I am trying to get the return value of the function. But in this version, I cannot even see any console.log output. What I mean by the version is, if I put 2nd line out of the async block without "await" keyword, I can see the console.log but I it gives "undefined" then.
(async () => {
const locationsData = await getPubsFromDatabase();
console.log(locationsData)
})()
3
Answers
I solved the problem by instead of returning the value from the function, I set the value inside the function. This seems to work now.
And to call the function:
You can use then and catch in the function fetch.
And when you use the method getPubsFromDatabase would be of the next way:
You can use Promise to return either result or error, In the example given below i have used axios library but you can also try same with fetch api
For Example
You can call the above function in component or screen like this: