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.
- You have declared
getAPI
inside your component. So you should probably add it to the array of dependencies ofuseEffect
. - You should call
getAPI
inonChange
of the input. So it fetches the data from server based on the query parameters. - You have not used
searchTerm
insidegetAPI
function. - Be aware of infinite loop caused by
useEffect
.