Home > Software design >  Unable to fix cannot read properties of undefined
Unable to fix cannot read properties of undefined

Time:04-13

I'm trying to remove this error but I'm unable to sort this issue, It's pretty obvious when there's no data to filter that happens and I want to avoid it

I have a function to filter out the data

const filteredItems = useMemo(() => {
    return results.filter((quote) => {
      const a = quote.customer_reference.toLowerCase().includes(customer_reference.toLowerCase())
      const b = quote.created_by.toLowerCase().includes(created_by.toLowerCase())
      const c = quote.quote_status.toLowerCase().includes(quote_status.toLowerCase())

      if (a && b && c) {
        return true
      }

      return false
    })
  })

Here results is a list of items from backed, and it takes a little time to load the data from the backend until then it crashes and gives that undefined error. And also I need the filtered list to pass into the data table, like here.

    <DataTable
      noHeader
      size="sm"
      pagination
      columns={advSearchColumns}
      paginationPerPage={7}
      className="table-sm"
      sortIcon={<ChevronDown size={10} />}
      paginationDefaultPage={currentPage   1}
      paginationComponent={CustomPagination}
      data={filteredItems} // Thats the filtered items 
    />

Full error ×

TypeError: Cannot read properties of undefined (reading 'filter')

CodePudding user response:

Based on a comment above, indicating that the error is thrown here:

return results.filter((quote) => {

If results is undefined then you can't "filter" anything on it. What should filteredItems return in that case? For example, you can perform null checking to return null:

return results?.filter((quote) => {

Or perhaps you could conditionally return an empty array:

return results ? results.filter((quote) => {
  //...
}) : [];
  • Related