DEV Community

Discussion on: Simple search form in REACT using hooks 🔎.

Collapse
 
abdullhrtima profile image
Abdullah Abu Rtima • Edited

call data from api and filter ....

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

export default function Search() {
    const [data ,setData] = useState([]);
    const [filtered ,setFilterd] = useState([]);
    const [result , setResult] = useState("");

    useEffect(()=>{
            const fetchData = async ()=> {
                    try{
                        const res = await axios.get('https://jsonplaceholder.typicode.com/users');
                        setData(res.data);
                        setFilterd(res.data);
                    }catch(err){
                        throw new Error(err);
                    }
                     };
                  fetchData(); 
        },[]);

        useEffect(()=> {
            const results = filtered.filter(res=> res.name.toLowerCase().includes(result)

            ); 
            setData(results)
        } ,[result])
        //console.log(data)

      const onChange =(e)=> {
            setResult(e.target.value);
        }

    return (
        <div>
        <input 
            type="text"
            placeholder="serch here .."
            value={result}
            onChange={onChange}
        />
        {data.map((r,i)=> (   
                <ul key={i}>
                <li>{r.name}</li>
                </ul>)
            )
        }
    </div>
    )  
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
moniqueboea profile image
moniqueboea

Thanks. I tried you exact code and get this warning:

29:6 warning React Hook useEffect has a missing dependency: 'filtered'. Either include it or remove the dependency array react-hooks/exhaustive-deps

Any suggestions?

My search isn't working

Collapse
 
moniqueboea profile image
moniqueboea

Actually, the search is working. I didn't realize that I had to type lower case. Can that be removed? Most people will start typing names in upper case (at least the first letter).

Collapse
 
amitdotcode profile image
amit-dotcode

codesandbox.io/s/unruffled-bose-tk...

Please Help Me .. See my Code
The problem is when I search in the search field to my note app its work but when I remove search field text my old add data not show only search data show see my code you better understand that what I m trying to say

Collapse
 
rhadimer profile image
Rhadimer Antigua Sánchez

Excellent!

Collapse
 
riad_bx profile image
Riad

thanks a lot !! you made my day..