Render A Functional Component After Fetching Data From A Post Api?
I want to re-render my component after the data fetched from my API. I used hooks to handle that. but it does not working. actually my component renders for the first time, not aft
Solution 1:
Simply updating the value of a variable won't trigger a render, however if you declare your labels as a state array using the useState()
hook updating it will.
Note: Using index as a key is an anti-pattern which will only lead to headaches later, choose a unique identifier for each element to use as key instead.
importReact, { useEffect, useState } from"react";
import getCities from"../functions/getCities";
importRadioListfrom"./RadioList";
exportdefaultfunctionListOfStates(props) {
const [labels, setLabels] = useState([]);
const cities = [];
useEffect(() => {
getCities(props.cityState).then((array) => {
for (let i = 0; i < array.response.length; i++) {
cities.push(array.response[i]);
}
setLabels([...cities]);
});
}, []);
return (
<>
{labels.length && labels.map((labels, index) =>
<RadioListactive={(labels === props.active)}key={labels.id}label={labels} />)}
</>
);
}
Post a Comment for "Render A Functional Component After Fetching Data From A Post Api?"