Home > Net >  ReactJs when I try to filter on search bar it gives TypeError: Cannot read properties of undefined (
ReactJs when I try to filter on search bar it gives TypeError: Cannot read properties of undefined (

Time:09-22

On console I get the data from my json server but when I try to type(filter) something it gives

1 of 1 unhandled error

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'filter') on onChangeHandler for filtering

import React, { useEffect, useState } from 'react'


export default function SearchBar() {
    const [users,setUsers] = useState ([])
    const [text,setText] = useState('');
    const [suggestions, setSuggestions] = useState([]);
    useEffect (() => {
        const loadUsers =async()=>
        {
            const response = await axios.get('http://localhost:800/content');
            setUsers(response.data.content)
            console.log(response.data)
        }
            loadUsers();
    },[])

    const onSuggestHandler =(text) =>  {
      setText(text);
      setSuggestions([]);
    }

    const onChangeHandler = (text) =>{
      let matches = []
      if (text.length>0)
      {
       matches = users.filter(user => {
        const regex = new RegExp(`${text}`,"gi");
        return user.title.match(regex);
       })
     
      }
      console.log("matches",matches)
      setSuggestions(matches)
      setText(text)
    }

  return (
    <div className='search'>
      <div className='search__container'>
        <h1>Search Bar</h1>
    <input type="text" 
    onChange={e=>onChangeHandler(e.target.value)}
    value={text}
    onKeyDown={e=>console.log(e)}
    />

    {suggestions && suggestions.map ((suggestions,i) =>
    <div className='suggestions' key={i}
    onClick = {()=>onSuggestHandler(suggestions.title)}
    >{suggestions.title}</div>
    )}

      </div>
    </div>
  )
}

CodePudding user response:

Seems that on the line where you have matches = users.filter, users is undefined, so you can't call filter() on it. Just adding a users?. would avoid a crash.

But it mean you have a logic issue and set your users with undefined at some point.

You might want to check your response.data.content and make sure what's inside.

  • Related