Home > other >  React.js API for search bar (please help, I'm hopeless)
React.js API for search bar (please help, I'm hopeless)

Time:08-07

I'm very new to javascript and the world of react. I've learning hooks, and tried to fetch some api for searchbar and it just doesn't work. Please help me.

I'm trying to grab the data from the url (it's array) and search bar to filter items by its title.

function Search() {
    const [searchTerm, setSearchTerm] = useState([]);
    const [text,setText] = useState([]);
    
    const getAPI = async() => {
        const response = await fetch("https://fakestoreapi.com/products")
        const data = await response.json()
        setText(data.Search)
    }

    useEffect( () => {
        getAPI()
    }, [])

    return <div>
            <input 
                placeholder="searching"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}/>
            </div>
};

CodePudding user response:

there is not any key with Search name inside response data you should setState all your data and then filter with input text value.

CodePudding user response:

Please read useEffect documentation.

    useEffect( () => {
        getAPI()
    }, [])

The above code only runs when the component is mounted. When the user changes the value of input, Search component rerenders, because its state changes. But useEffect will not be executed because you have provided an empty array of dependencies.

  1. You have declared getAPI inside your component. So you should probably add it to the array of dependencies of useEffect.
  2. You should call getAPI in onChange of the input. So it fetches the data from server based on the query parameters.
  3. You have not used searchTerm inside getAPI function.
  4. Be aware of infinite loop caused by useEffect.
  • Related