javascriptreactjseventsreact-hooks

Cannot read property of undefined React Hooks


I am trying to create a search feature using react hooks but it keeps returning the error:

Cannot read Property of Undefined

on the updateSearch function whenever I type in the input field.

  const [search, setSearch] = React.useState('');
  const [searchResults, setSearchResults] = React.useState([]);

  const [state, setState] = React.useState({
    open: false,
    name: '',
    users:[]
  });

  useEffect(() => {
    getAllUsers();
  }, []);


  const getAllUsers = () => {
    fetch('/userinformation/', { 
      method: 'GET',
      headers: {'Content-Type':'application/json'}
    })
    .then(function(response) {
      return response.json()
    }).then(function(body) {
      console.log(body);
      setState({...state, users: body });
    })
  }

  const updateSearch = (event) => {
   setSearch(event.target.value)
  }

  React.useEffect(() => {
    const results = state.users.filter(user =>
      user.toLowerCase().includes(search)
    );
    setSearchResults(results);
  }, [search]);

return (
<input type="text" value={search} onChange={(e) => updateSearch(e.target.value)}/>
)

Whenever I type in the search bar I get the following error: enter image description here

How can i fix this?


Solution

  • You can either get to the value of passed event by changing

    <input type="text" value={search} onChange={(event) => updateSearch(event}/>
    

    or you can keep the input element as it is and change the update updateSearch callback to

    const updateSearch = (event) => { setSearch(event) }
    

    Secondly, you are applying includes to a single item of an array which is specific to array methods, you need to make following changes as well to make it work:

    React.useEffect(() => { 
     const results = state.users.filter( user => user.firstName.toLowerCase() === search ); 
     setSearchResults(results); 
    }, [search])