R
R
Roma2021-06-04 20:05:30
JavaScript
Roma, 2021-06-04 20:05:30

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());
      })

TypeError: Cannot read property 'Countries' of undefined. Why is an array of objects not recognized and filtered?
In another file, the map method iterates over the same spelling data.Countries without error.
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

2 answer(s)
K
Konstantin, 2021-06-04
@Roma23

Most likely, the error occurs during the first render, since your variable datacontains 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;

K
Kirill Makarov, 2021-06-05
@kirbi1996

data?.Countries?.filter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question