Search code examples
reactjsapireact-hooksuisearchbar

TypeError: Cannot read property 'toLowerCase' of undefined in React-hooks


I'm making a search bar. However, an error occurs.

If you erase 'toLowerCase', the next 'includes' will fail. I keep getting an error.

The data was received without any problem.

Why did you do that? I'm a beginner. Help me, please.

Data from the console log.

enter image description here

import React, { useState, useEffect } from "react";
import axios from "axios";

const Searchs = () => {
  const url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s";

  const [searchTerm, setSearchTerm] = useState("");
  const [searchValue, setSearchValue] = useState("");
  const [results, setResults] = useState([]);

  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        console.log(res);
        setResults(res.data.drinks);
        console.log(res.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);
  const searchHandler = (value) => {
    setSearchValue(value);
  };
  let updateUsers = results.filter(({ strdrink }) => {
    return strdrink.toLowerCase.includes(searchValue);
  }, []);
  const handleSearchInputChange = (e) => {
    searchHandler(e.target.value);
  };

  return (
    <Wrapper>
      <form>
        <input
          type="text"
          placeholder="재료 또는 이름을 검색하세요"
          value={searchTerm}
          onChange={handleSearchInputChange}
        />
      </form>
      <ul>
        {(searchValue === "" ? results : updateUsers).map(
          ({ idDrink, strAlcoholic, strDrinkThumb, strDrink }) => (
            <li key={`${idDrink}`}>
              <br />
              {`${strDrink}`} <br />
              {`${strAlcoholic}`} <br />
              {`${strDrinkThumb}`}
            </li>
          )
        )}
      </ul>
    </Wrapper>
  );
};
export default Searchs;

Solution

  • Two changes here

    `return strdrink.toLowerCase.includes(searchValue);`
    

    Change strdrink to strDrink. Keys are case sensitive

    toLowerCase is a function. Use like toLowerCase()