[英]How to make an API call using onClick function to render a list of data in React?
I want to fetch data for a dependent API call and render the returned data as a list or table.我想为依赖的 API 调用获取数据并将返回的数据呈现为列表或表。 Here's my code below
下面是我的代码
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;
The idea is, Lga is a dropdown while wards should be a list and details is a list.这个想法是,Lga 是一个下拉列表,而 wards 应该是一个列表,而 details 是一个列表。 The lga fetch works fine.
lga fetch 工作正常。 on selected lga, a fuction triggers to list the wards.
在选定的 lga 上,会触发一个函数来列出病房。 finally onclick on the p tags triggers to fetch the details.
最后,p 标签上的 onclick 触发以获取详细信息。 my issues lies on the handleFac function as it returns an empty array thus not rendering on the UI.
我的问题在于 handleFac function 因为它返回一个空数组,因此不会在 UI 上呈现。 please what am i doing wrong here.
请问我在这里做错了什么。 I appreciate any idea or help
我感谢任何想法或帮助
Issue is e.target.value
was undefined
for onClick
handler for p
tags.问题是
undefined
为p
标签的onClick
处理程序定义e.target.value
。
onClick
handler invoking like below.onClick
处理程序调用,如下所示。<p
...
...
onClick={() => handleFac(dep)}
...
>
{dep}
</p>
handleFac
like below.handleFac
。const handleFac = dep => {
Axios.get(`https://pshs3.herokuapp.com/${dep}/ward/details`).then(
response => {
const details = response.data.data;
setFacility(details);
}
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.