How To Export The Response Data Obtained From A Get Api Using Fetch From One Module To Another
Code Snippet: let data ={}; zlFetch('http://localhost:3000/new.json') .then(response => handleget(response)) .catch(error => console.log(error)); function
Solution 1:
You can't.
It is asynchronous.
The export of the value of data
happens before the response has been received.
Assign the promise returned from catch
to data
instead.
Then deal with the promise after you import it.
const data = zlFetch('http://localhost:3000/new.json')
.then(response => resonse.body)
.catch(error =>console.log(error));
exportdefault data;
Later
import newthing from'./myModule';
newthing.then(data => ...);
Solution 2:
Using the answer provided by Quentin, here is how my final code looks like along with error handling from fetch request
//Logic.jsconst data = zlFetch('http://localhost:3000/new.json')
.then(response => response)
.catch(error =>console.log(error));
exportdefault data
//App.jsimport data from"./Logic.js";
asyncfunctionfetch_this_data()
{
const res = await data.then(result => result);
if (res.status == 200)
{
console.log("res"+JSON.stringify(res.body));
return res.body;
}
else
{
console.log("resu"+JSON.stringify(res));
return"Error!! Status "+res.status;
}
}
fetch_this_data();
Post a Comment for "How To Export The Response Data Obtained From A Get Api Using Fetch From One Module To Another"