Reputation: 409
I have a component and fetch data from an API (https://restcountries.eu/rest/v2/all). It is an array of objects. I want to pass some of the info of that object to a state but it gets stuck in a loop.
function AllCountries() {
const [countries, setCountries] = useState([]);
fetch(`https://restcountries.eu/rest/v2/all`)
.then((r) => r.json())
.then((data) => {
if (data!== undefined) {
data.map((ob) => {
setCountries(
...countries,{
flag: ob.flag,
name: ob.name,
population: ob.population,
region: ob.region,
capital: ob.capital}
);
});
//console.log(countries);
} else {
alert("Can´t Load Data");
}
});
return (
<div>PRUEBA</div>
);
}
Upvotes: 1
Views: 2173
Reputation: 55623
It needs to be wrapped in useEffect
:
function AllCountries() {
const [countries, setCountries] = useState([]);
useEffect(() => {
fetch(`https://restcountries.eu/rest/v2/all`)
.then((r) => r.json())
.then((data) => {
if (data!== undefined) {
data.map((ob) => {
setCountries(
...countries,{
flag: ob.flag,
name: ob.name,
population: ob.population,
region: ob.region,
capital: ob.capital}
);
});
//console.log(countries);
} else {
alert("Can´t Load Data");
}
});
},[]);
return (
<div>PRUEBA</div>
);
}
Otherwise, the fetch
will get executed every time the component is rendered.
Furthe reading: https://reactjs.org/docs/hooks-effect.html
Upvotes: 2