0
  1. I am trying to add Seach filter using the react, and using json data I am trying to match it with the search term

  2. Below is my code

    const App = () => { const [searchTerm, setSearchTerm] = useState([""]) const [query, setQuery] = useState("");

    useEffect(() => { const url = "https://60d075407de0b20017108b89.mockapi.io/api/v1/animals";

    const fetchData = async () =>
      {
              try
          {
              const response = await fetch(url);
              const json = await response.json();
              console.log([json].query);
              setQuery(json.query);
          }
              catch (error)
          {
              console.log("error", error);
          }
      };
      fetchData();
    

    }, []);

    return ( <input type='text' placeholder='search....' onChange={event => { setSearchTerm(event.target.value) }} />

      {
    
              query.filter((val) => {
                if (searchTerm === "s")
          {
              return val
          }
              else if (val.name.toLowerCase().includes(searchTerm.toLowerCase())) {
              return val
          }
          else
              return false
          }).map((val) =>
          {
              return (
              <div className='user' >
              <p>{val.name}</p>
              <p>age: {monthDiff(val.bornAt)} months</p>
    
            </div>
          );
          })}
    </div>
    

    ); };

When I try to execute, I am getting this below error can anyone explain why it is happening

> Uncaught TypeError: Cannot read properties of undefined (reading
> 'toLowerCase')
1
  • Welcome to SO! Are you able to fix the formatting if your code? I think you have a few ` s out of place :) Commented Dec 22, 2021 at 4:40

1 Answer 1

1

It looks like you're initializing query to a string instead of an array of strings.

Maybe try changing this:

const [query, setQuery] = useState("");

to

const [query, setQuery] = useState([""]);

Also, your searchTerm is initialized to an array: you might have just mixed those up :)

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, thank you for identifying this issue. There is no error now!!
You're welcome! If this helped you can mark the answer as accepted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.