Answer the question
In order to leave comments, you need to log in
TypeError: Cannot read property 'Countries' of undefined. Why is an array of objects not recognized?
I am getting object from API( https://api.covid19api.com/summary ). This object has a key Countries with an array of objects and I need to filter this array of objects.
const filteredData = data.Countries.filter(dat => {
return dat.Country.toLowerCase().includes(searchfield.toLowerCase());
})
const Home = () => {
const [data, setData] = useState();
const [searchfield, setSearchfield] = useState('')
useEffect(() => {
const fetch = async () => {
try{
const res = await axios.get('https://api.covid19api.com/summary');
setData(res.data);
}catch(error){
console.log(error);
}
};
fetch();
}, []);
const onSearchChange = (event) => {
setSearchfield(event.target.value)
}
const filteredData = data.Countries.filter(dat => {
return dat.Country.toLowerCase().includes(searchfield.toLowerCase());
})
return (
<div className="main-container">
<Header searchChange={onSearchChange}/>
<div className="wrapper">
<Card data={data}/>
{/*<div className="graph">
<h1>Global Pandemic Crisis Graph</h1>
<img src={COVID.image} alt=""/>
</div>*/}
<div className="countries">
<Countries data={filteredData}/>
</div>
</div>
{/*<Footer />*/}
</div>
)
}
export default Home;
Answer the question
In order to leave comments, you need to log in
Most likely, the error occurs during the first render, since your variable data
contains undefined, and not an object with a field . Countries
There are different solutions:
1. You can create a variable not data
, but countries
, where the array will lie, not the object. And in this case, you can set the default value:
const [countries, setCountries = useState([]);
Plus, you still need to rewrite some pieces of code
2. You can add a check for `undefined`:
const filteredData = data && data.Countries
? data.Countries.filter(dat => {
return dat.Country.toLowerCase().includes(searchfield.toLowerCase());
})
: undefined;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question