reactjsredux

search input field according to the value (API)


I have an api call like this: api/zipCode/${zipCode}

So, I have an input field and the user enters the zip code and what I want to make is if the user enters 3 digits I want to show the matched zip codes. For example,e if the user enters 123 I want to show 123, 1234, 1233 etc. Since I have no idea how to build this, I am looking for you helps. Any idea would be precious.


Solution

  • Please find the solution below

    Also, You can see the live demo

    https://codesandbox.io/s/pedantic-lichterman-1rqjf?file=/src/App.js:0-1190

    import { useEffect, useState, useMemo } from "react";
    
    const endPoint = "https://jsonplaceholder.typicode.com/users";
    
    export default function App() {
      const [users, setUsers] = useState([]);
      const [loading, setLoading] = useState(true);
      const [searchText, setSearchText] = useState("");
    
      useEffect(() => {
        (async function () {
          const res = await fetch(endPoint);
          const data = await res.json();
          setUsers(data);
          setLoading(false);
        })();
      }, []);
    
      const filterData = useMemo(() => {
        if (searchText.length > 3) {
          return users.filter((user) => user.address.zipcode.includes(searchText));
        }
        return null;
      }, [users, searchText]);
    
      if (loading) return <p>Loading...</p>;
    
      return (
        <div className="App">
          <h1>Type in searchbox to get the user with matching zipcode</h1>
          <input
            type="text"
            placeholder="Search Zip"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
          />
          <ul>
            {filterData &&
              filterData.map((data) => (
                <li key={data.id}>{data.address.zipcode}</li>
              ))}
          </ul>
        </div>
      );
    }