Reputation: 35
I'm trying to return the prop name from this api https://restcountries.eu/rest/v2/name/france but the console return only undefined. Somebody can help-me?
useEffect(() => {
if(selectedCountry === '0'){
return
}
axios.get<Country>(`https://restcountries.eu/rest/v2/name/france`).then(response => {
const {name} = response.data
console.log(name)
})
})
Upvotes: 1
Views: 333
Reputation: 21
Observing the returned data, response data is an array instead of an object.
[{"name":"France","topLevelDomain":[".fr"],"alpha2Code":"FR","alpha3Code":"FRA","callingCodes":["33"],"capital":"Paris","altSpellings":["FR","French Republic","République française"],"region":"Europe","subregion":"Western Europe","population":66710000,"latlng":[46.0,2.0],"demonym":"French","area":640679.0,"gini":32.7,"timezones":["UTC-10:00","UTC-09:30","UTC-09:00","UTC-08:00","UTC-04:00","UTC-03:00","UTC+01:00","UTC+03:00","UTC+04:00","UTC+05:00","UTC+11:00","UTC+12:00"],"borders":["AND","BEL","DEU","ITA","LUX","MCO","ESP","CHE"],"nativeName":"France","numericCode":"250","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Frankreich","es":"Francia","fr":"France","ja":"フランス","it":"Francia","br":"França","pt":"França","nl":"Frankrijk","hr":"Francuska","fa":"فرانسه"},"flag":"https://restcountries.eu/data/fra.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"FRA"}]
so you should treat response data as an array, like this
axios.get('https://restcountries.eu/rest/v2/name/france').
then(response => {
console.log(response)
const [extractedData] = response.data //response.data is an array, and you extract the content to extractedData
const {name, topLevelDomain}= extractedData //extractedData is an object, so you can use braces to visit fields with their name
console.log(data)
console.log(name)
console.log(topLevelDomain)
})
Upvotes: 0
Reputation: 888
The response from that GET request is an array:
[
{
"name": "France",
...
}
]
Since the response returned is an array, so you need to index the first item.
useEffect(() => {
if (selectedCountry === '0') {
return
}
axios.get('https://restcountries.eu/rest/v2/name/france')
.then(response => {
const { name } = response.data[0]
console.log(name)
})
})
In the future, you can try printing the entire response first to make sure you understand the shape of the data.
Upvotes: 0
Reputation: 11
Since the data returned from the service is an array, you should read the name prop of response.data[0]
useEffect(() => {
if (selectedCountry === '0') {
return
}
axios.get(`https://restcountries.eu/rest/v2/name/france`).then(response => {
const {name} = response.data[0]
console.log(name)
})
},[])
Upvotes: 1