I'm trying to fetch data from a local json-server and display it in a list using react.
From my understanding the useEffect should trigger a console log twice in this instance. One empty return for the countries and one populated one.
If someone is able to let me know why this console.log get's triggered so often I'd be really thankful.
The react code:
import React, { useEffect, useState } from 'react'
export default function CountryList() {
const [countries, setCountries] = useState([])
useEffect(() => {
fetch('http://localhost:3001/countries')
.then(res => res.json())
.then(data => setCountries(data))
}, [])
console.log(countries)
return (
<div>
<h2>CountryList</h2>
<ul>
{countries.map(country => (
<li key={country.name}>{country.name}</li>
))}
</ul>
</div>
)
}
The console however returns the following:
The json-server get's this list of countries:
{
"countries": [
{
"name": "Austria",
"code": "AT",
"language": "german",
"cities": {
"Vienna": {
"population": "8.3 million",
"latitude": "48.208174",
"longitude": "16.373819"
},
"Graz": {
"population": "1.5 million",
"latitude": "47.070713",
"longitude": "15.439186"
}
},
"currency": {
"code": "EUR",
"name": "Euro",
"symbol": "€"
}
},
{
"name": "Greece",
"code": "GR",
"language": "greek",
"cities": {
"Athens": {
"population": "2.7 million",
"latitude": "37.983810",
"longitude": "23.727539"
},
"Thessaloniki": {
"population": "1.5 million",
"latitude": "40.633125",
"longitude": "22.944406"
},
"Patras": {
"population": "1.5 million",
"latitude": "38.244818",
"longitude": "21.738050"
}
},
"currency": {
"code": "EUR",
"name": "Euro",
"symbol": "€"
}
}
]
}