Search filter with React

Asked

Viewed 747 times

1

I am studying Javascript and need to do a data filtering based on what the person type and delete in input dynamically. I searched and could not implement in my code, I am using the useEffect() to pick up the main news and is already working, but I can not do the search.

useEffect(() => {
    api.get('/v2/top-headlines?country=br&apiKey=85444b264aa246f28c5f41494efd6e03').then(async response => {
        setNews(response.data.articles)
    })
});

  return (
      <>
        <Navbar />

        <div className="row px-5 input-area">
            <input onChange={(e) => setSearch(e.target.value)} type="text" className="form-control text-center input-text" placeholder="Search News" />
        </div>

        <div className="row">
            {news.map(news => (
                <div className="col-md-6">
                    <Card img={news.urlToImage} title={news.title} description={news.description} author={news.source.name} url={news.url} key={news.source.name} />
                </div> //
            ))}
        </div>
    </>
  )
}

If anyone can help me I would be eternally grateful <3.

  • The search already picks up all the news and you will filter the data already collected or you will fetch the news when the input content changes?

  • I want to load the page with all the content of the API, which has type a request that returns the most relevant results according to the parameter used 'country=br' if put us will bring relevant news from the US, but have another request with a parameter type search, 'q=memesdegatos' then it will fetch news related to this parameter. Dai want to put in the input onChange for it to trigger a function that searches according to that search.

  • Now my request limit the API has exceeded today, so you can only test it tomorrow =(

1 answer

1


The useEffect has an array of dependencies, ALL states you place within that array will cause the entire process within useEffect to occur again whenever any of these states change. Example:

useEffect(() => {
   console.log('olá mundo')
}, [estado1, estado2])

// Aqui, **sempre que o estado1 ou o estado2 mudar, o console.log será executado**

We can use the dependency array to solve your problem:

const [search, setSearch] = useState('') //estado que irá guardar o valor do input

useEffect(() => {
 let apiEndpoint = '/v2/top-headlines?country=br&apiKey=85444b264aa246f28c5f41494efd6e03'

 if(search.length !== 0) {        //se o valor do input conter alguma informação, coloca-la na query para filtrar as noticias
   apiEndpoint += `&q=${search}'
 }

 api.get(apiEndpoint).then(async response => {
        setNews(response.data.articles)
 })

}, [search]) // repete o processo sempre que o valor do input mudar

return (
      <>
        <Navbar />

        <div className="row px-5 input-area">
            <input onChange={(e) => setSearch(e.target.value)} type="text" className="form-control text-center input-text" placeholder="Search News" />
        </div>

        <div className="row">
            {news.map(news => (
                <div className="col-md-6">
                    <Card img={news.urlToImage} title={news.title} description={news.description} author={news.source.name} url={news.url} key={news.source.name} />
                </div> //
            ))}
        </div>
    </>
  )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.