Forgive the ignorance, I'm not great with JavaScript (yet). I'm trying to fetch public user data from GitHub and display it on my personal portfolio. Currently I have the code below:
getData(url) {
return fetch(url);
}
const userData = getData("https://api.github.com/users/userName");
userData
.then((response) => response.json())
.then((response) => console.log(response))
.catch((error) =>
console.log("There was an error fetching the data: " + error)
);
console.log(userData)
The response I get is the JSON with the user data but when I console.log(userData) I get Promise { <state>: "pending" } as the response.
Also, I can see that there is an id in the initial response but when I console.log(userData.id) I get undefined.
I've read the GitHub API docs and watched a few videos on Promises but I can't seem to get my code to work correctly.
Thanks for taking the time to look at this and any help with this is greatly appreciated!
It is because userData is a promise. If you try using async/await (documentation is available here) you'll be able to synchronously get the data.
const getData = async (url) => {
try {
const data = await fetch("https://api.github.com/users/:user_name");
console.log(data.json());
return data;
} catch (e) {
console.log("There was an error fetching the data: " + error)
}
}
Related
I'm in react Native, and I have a request that im making using axios, and the request is supposed to return something like this:
Json data
I want to be able to save only the "Products" array in a variable.
This is the snippet of my cod, but it's giving me a 'Possible unhandled promise rejection' and I dont understand why:
const [shoesData, setShoesData] = useState([]);
useEffect(() => {
const getShoesData = async () => {
await axios.get("https://stockx.com/api/browse?productCategory=sneakers&sort=release_date&releaseTime=gte-" + Date.now().toLocaleString() + "&order=ASC&country=FR")
.then(response => {
let products = response.data.map(x => {
return x.products;
});
setShoesData(products);
console.log(products);
})
}
getShoesData();
}, [])
Thanks in advance for your help.
Try and wrap your await instruction with a try catch. One possible error can be that the data you get from the response can, in some cases, not have a products field.
I'm looking for a way of handling errors with the native javascript fetch api. Used to use jQuery, but I'm trying to use more native javascript functions.
I found this blog and like the approach: https://learnwithparam.com/blog/how-to-handle-fetch-errors/
fetch(url)
.then((response) => {
if (response.status >= 200 && response.status <= 299) {
return response.json();
}
throw Error(response.statusText);
})
.then((jsonResponse) => {
// do whatever you want with the JSON response
}).catch((error) => {
// Handle the error
console.log(error);
});
However, in the catch I'm getting the statusText that belongs to the HTTP code. For 400 for example Bad request. But that is not wat I want, my call to the server will respond with exactly what is wrong. So I want to use the response body text as a the error. I tried different ways, but I can't get the response body incase the HTTP code is 400. With jQuery I used response.responseJSON.html. But this is not available with the fetch api.
So how can I can use the response body as error code.
The fetch API was designed to work best with async functions. If you can make your outer function async, your code would become:
try {
const response = await fetch(url);
if (!response.ok) {
const text = await response.text();
throw Error(text);
}
const jsonResponse = await response.json();
// do whatever you want with the JSON response
} catch (error) {
console.log(error);
}
Otherwise, it gets a bit more complicated:
fetch(url)
.then((response) => {
if (response.ok) {
return response.json();
}
return response.text().then((text) => throw Error(text));
})
.then((jsonResponse) => {
// do whatever you want with the JSON response
}).catch((error) => {
// Handle the error
console.log(error);
});
*New to express.
I have index.ejs and script.js.
My script fetches some JSON data from an api just fine.
const fetch = require("node-fetch");
const url = '...'
fetch (url)
.then(response => {
return response.json()
})
.then(data =>{
console.log(data)
})
.catch(err => {
})
How would I go about using this returned JSON data to create a chart in my index page with d3.
I have searched around but am still confused. Any advice would be super helpful! Thanks.
So as discussed in the comments, the problem was having a server which is return in express framework of nodejs
So in express code need to call an api and get data, once we get the data we need to send it to the front end.
So for returning data to front end we can use res.send of express
const fetch = require("node-fetch");
const url = '...'
fetch (url)
.then(response => {
return response.json()
})
.then(data =>{
console.log(data)
res.send(data)
})
.catch(err => {
})
And in the front end we need to access this api as shown below
const getData = async () => {
try {
const response = await fetch(url) // server url (express js route) example http://localhost:6000/api/getChartData
if(response.ok){
const body = await response.json()
console.log(body)
// once you get the data you can create d3 chart
return
}
const customError = {
message: 'something went wrong'
}
throw customError
}catch(error){
console.log(error)
// put the error in a variable and display on the ui so the user know some error happened
}
}
I have a requirement to display all the countries in the world in a drop down.
So I found this api end point END POINT LINK. When I copy and paste this end point link in my web browser I got a response with all the data. (countries);
When I try to embed this in project.
getCountries() {
try {
fetch(`https://restcountries.eu/rest/v1/all`).then(data =>
console.log(data)
);
} catch (error) {
console.log("HERE ERROR COMES", error);
}
}
It does go to then block of the fetch method. But gives me the output
There is nothing called data here. Even I get a success respond.
Why could this happen? Is this something related to cors errors?
You can use as follow:
let url = 'https://restcountries.eu/rest/v1/all';
fetch(url)
.then(res => res.json())
.then((data) => {
console.log(data);
})
.catch(err => { throw err });
This works for me
function getCountries(){
fetch("https://api.printful.com/countries ")
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
let countries = data.result;
return countries.map(function(country){
console.log(country.name);
//Create your list here
});
});
}
responce.type 'cors' probably means Cross Origin Request - and it's blocking it - try to find another api
I'm trying to manipulate JSON data received from an API url (this is my first time handling this type of work)
The following function returns a promise of a 20 element array:
const articles = () => {
return fetch(url)
.then(res => res.json())
.then(post => post.articles);
};
Console view:
Now, I'd like to extract the elements from the array - I tried something like:
articles()[0].name
but this doesn't work and I'm not sure of an alternative way to go about this? Appreciate your help. Thanks
Your articles fucntion returns a promise. You have to consume the promise (more on MDN):
articles().then(articleArray => {
console.log(articleArray);
});
or within an async function:
const articleArray = await articles();
console.log(articleArray);
Side note: Your fetch code is missing a check for HTTP success (HTTP failure isn't a rejection). You're by far not the only person who misses out this check, so much so that I've written a post on my anemic blog about it. With the check:
const articles = () => {
return fetch(url)
.then(res => {
if (!res.ok) {
throw new Error("HTTP error " + res.status);
}
return res.json();
})
.then(post => post.articles);
};