I’m trying to make Covid-19 tracker App by ReactJS.
I want to get data that only an object (a specific province value) from JSON API with ProvinceChange event.
the problem
I can’t get data that only an object (a specific province value).
what I tried
I tried method filter using province.name but is not work,like I get
enter image description here
Sample JSON API
[
{
"txn_date": "2022-03-07",
"province": "กระบี่",
"new_case": 112,
"total_case": 18101,
"new_case_excludeabroad": 112,
"total_case_excludeabroad": 17838,
"new_death": 2,
"total_death": 93,
"update_date": "2022-03-07 07:20:43"
},
{
"txn_date": "2022-03-07",
"province": "กรุงเทพมหานคร",
"new_case": 2815,
"total_case": 590810,
"new_case_excludeabroad": 2809,
"total_case_excludeabroad": 587121,
"new_death": 7,
"total_death": 7126,
"update_date": "2022-03-07 07:20:43"
},
{
"txn_date": "2022-03-07",
"province": "กาญจนบุรี",
"new_case": 176,
"total_case": 33734,
"new_case_excludeabroad": 176,
"total_case_excludeabroad": 33684,
"new_death": 2,
"total_death": 214,
"update_date": "2022-03-07 07:20:43"
},
{
"txn_date": "2022-03-07",
"province": "กาฬสินธุ์",
"new_case": 214,
"total_case": 18163,
"new_case_excludeabroad": 214,
"total_case_excludeabroad": 18159,
"new_death": 0,
"total_death": 97,
"update_date": "2022-03-07 07:20:43"
},]
This is my code
const App = ()=>{
const [provinces, setProvinces] = useState([]);
const [province, setProvince] = useState("thailand");
const [provinceInfo, setProvinceInfo] = useState({});
useEffect(() => {
const getProvincesData = async () => {
fetch("https://covid19.ddc.moph.go.th/api/Cases/today-cases-by-provinces")
.then((response) => response.json())
.then((data) => {
const provinces = data.map((province) => ({
name: province.province,
}));
setProvinces(provinces);
});
};
getProvincesData();
}, []);
const onProvinceChange = async (event) =>{
const provinceCode = event.target.value;
//setProvince(provinceCode);
const url =
provinceCode === "thailand"
? "https://covid19.ddc.moph.go.th/api/Cases/today-cases-all"
: 'https://covid19.ddc.moph.go.th/api/Cases/today-cases-by-provinces' ;
await fetch(url)
.then(response => response.json())
.then(data => {
const provinceInfo = data.filter((data) => {
return data.name === '{province.name}'
})
setProvince(provinceCode);
// All of the data from the province response
setProvinceInfo(data);
});
};
console.log(provinceInfo);
return (
<div className="app">
<div className='app__left'>
<div className="app__header">
<h1>COVID-19 TRACKER in Thailand</h1>
<FormControl>
<Select variant="outlined" onChange={onProvinceChange} value={province}>
<MenuItem value="thailand">ประเทศไทย</MenuItem>
{provinces.map((province) => (
<MenuItem value={province.name}>{province.name}</MenuItem> // Loop through all the province and show drop down list of the option
))}
</Select>
</FormControl>
</div>
</div>
);
}