'How to render the first data from API on page load
I have a dependent API call. I want to be able to render the a list of details on page load. See my code below for insight:
function Informal() {
const [myLga, setMyLga] = useState([]);
const [ward, setWard] = useState([]);
const [wardCount, setWardCount] = useState([]);
const [facility, setFacility] = useState([]);
const [selectedLga, setSelectedLga] = useState("");
const getLga = async (e) => {
try {
const fetchLocal = await Axios.get(
"https://pshs3.herokuapp.com/informal/counts"
);
const item = Object.keys(fetchLocal.data.data);
setMyLga(item);
} catch (err) {
console.log(err);
}
};
const handleWard = (e) => {
const result = e.target.value;
Axios.get(`https://pshs3.herokuapp.com/${result}/informal/counts`).then(
(response) => {
const myWard = Object.keys(response.data.data);
setWard(myWard);
}
);
};
const handleFac = (e) => {
const output = e.target.value
Axios.get(
`https://pshs3.herokuapp.com/${output}/ward/details`
).then((response) => {
const details = response.data.data;
console.log(details)
});
};
useEffect(() => {
getLga();
}, []);
return (
<Container >
<div>
//Lga
<TextField
name="lga"
select
label="LGA"
value={selectedLga}
onChange={handleWard}
SelectProps={{
native: true,
}}
sx={{
width: "23ch",
}}
>
<option value="">Select LGA </option>
{myLga?.map((curr) => (
<option key={curr}>{curr}</option>
))}
</TextField>
//wards
<div>
<div>
{ward?.map((dep, id) => (
<p
style={{
cursor: "pointer",
borderLeft: "2px green",
borderLeftStyle: "solid",
paddingLeft: "5px",
}}
onClick={handleFac}
key={id}
>
{dep}
</p>
))}
</div>
</div>
//list of details
<div>
<h4>Details</h4>
<ul>
{facility?.map((tul, index) => (
<li key={index}>{tul.name}</li>
))}
</ul>
</div>
</div>
</Container>
);
}
export default Informal;
I want to be able to load the first item from the getLga function which in turn renders its corresponding LIST of data from the handleWard function and finally renders the corresponding dataLIST from the handleFac function. Then users can now select any desired option so the API makes another call.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
