skip to Main Content

I made a simple search bar but the first time you type something in it you get
Cannot read properties of undefined (reading 'toLowerCase') TypeError: Cannot read properties of undefined (reading 'toLowerCase')
when i close the pop up and type the search bar works

function Search(event) {
    setQuery(event.target.value);

    if (event.target.value === '') {
        setFilteredData(backendData);
    } else {
        setFilteredData(filteredData.filter(el => el.childName.toLowerCase().includes(query.toLowerCase())));
    }
}

4

Answers


  1. you can try this

    setFilteredData(filteredData.filter((el) => {
        console.log('el', el);
        if (el && typeof el?.childName == 'string' && typeof query == 'string') {
            return el?.childName?.toLowerCase()?.includes(query?.toLowerCase())
        } else return false;
    }));
    
    Login or Signup to reply.
  2. It seems like the first time the el.childName or query are undefined.

    Could you try this?

    function Search(event) {
        setQuery(event.target.value);
    
        if (event.target.value === '' || !el.childName || !query) {
            setFilteredData(backendData);
        } else {
            setFilteredData(filteredData.filter(el => el.childName.toLowerCase().includes(query.toLowerCase())));
        }
    }
    
    Login or Signup to reply.
  3. Your filter data or query is undefined.

    function Search(event) {
        setQuery(event.target.value);
    
        if (event.target.value === '') {
            setFilteredData(backendData);
        } else {
            setFilteredData(filteredData => filteredData?.filter(el => el.childName.toLowerCase().includes(query?.toLowerCase())));
        }
    }
    
    Login or Signup to reply.
  4. I don’t think you should set query and filteredData in the same function (that makes query state itself pointless). A more common approach is to use a useEffect to change the filteredData accordingly:

    function Search(event) {
        setQuery(event.target.value);
    }
    
    useEffect(() => {
        if (!backendData) return;
    
        if (query) {
            setFilteredData(backendData.filter(el => el.childName.toLowerCase().includes(query.toLowerCase())));
        } else {
            setFilteredData(backendData);
        }
    }, [query, backendData]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search