0

I am trying to implement a search bar. After filling in the input text field, an empty array is being returned when I am clicking on the search button for the first time. However on subsequent clicks, correct data is being returned. Why is this happening?

Sharing snippets of my code:

   function Search(){
       const [person, setPerson] = useState('');
       const [movie_res, setMovie_res] = useState([])
        
       const onClickHandler = async () =>{
        axios.get('https://api.themoviedb.org/3/search/movie?api_key=***&language=en-US&query=' + person + '&page=1&include_adult=false').then(
            res => {
                setMovie_res(res.data.results)
                console.log(movie_res);
            }
        ).catch('SEARCH ERROR!!')
    }
    return(
...
         <TextField id="filled-basic" label="Search" variant="filled" onChange = {event => setPerson(event.target.value)} />

        <Button onClick = {onClickHandler}>In Movies  </Button>
   )

}

How can I fix this? Also attaching SS enter image description here

abc
  • 59
  • 6

2 Answers2

0

It is returning the data properly,you not testing it properly,do it like this:

useEffect(()=>{
console.log(movie_res);
},[movie_res]);

This useEffect comes into the picture as soon as the value of movie_res gets updated and hence prints the most recent value.

Sakshi
  • 1,464
  • 2
  • 8
  • 15
0

because setState is async. when you write:

     setMovie_res(res.data.results) // this is async, it doesn't update right away
     console.log(movie_res); // console.log runs before movie_res finish updated, so you are printing value before being updated
buzatto
  • 9,704
  • 5
  • 24
  • 33