Cannot read property of undefined error when trying search from api using react

I am currently attempting to create a search bar to search from API in which rendering what i am search for. But when I write the code to filter the API

const filterStudents = data.students.filter((student) => {
    return student.firstName.toLowerCase().includes(search.toLowerCase());

it’s working for seconds then it give me this error
Cannot read property 'students' of undefined.
The code is here:

At some point this line is called when data is not defined (presumably before the API response has arrived). Typically, when accessing object properties, you want your code to check that the object exists and has the property that you’re looking for.

The most straightforward way to do this is:

let filterStudents = [];
if (data && data.students){
    filterStudents = ....

Looking back to ternaries you may have thought “Why would I use these? They’re confusing!” or been excited and tried to use ternaries everywhere only to have people say “Ternaries should be used sparingly. They’re hard to read.” Well, this is one of those situations where ternaries are very commonly used:

const filterStudents = (data && data.students) ? data.students.filter(...) : [];

Now, if you’re using TypeScript, you get this cool syntactic sugar called “optional chaining”. In that case you can write the same logic as:

const filterStudents = data?.students?.filter(...);

Thanks for your detailed explanation. :clap: