0

I'm working on a project that makes an api request, but my request is being called 4 times, why is this happening?

const [movies, setMovies] = useState([]);
  const [searchTerm, setSearchTerm] = useState('')

  useEffect(() => {

    getMovies(FEATURED_API)
    
    if (searchTerm) {
      getMovies(SEARCH_API + searchTerm);
    } else{
      getMovies(FEATURED_API)
    }

  }, [searchTerm])


  const getMovies = (API) => {
    fetch(API)
    .then((res) => res.json())
    .then((data) => {
      console.log(data)
      setMovies(data.results)
    })
  }

  const handleOnChange = (e) => {
    setSearchTerm(e.target.value)
  }```

1 Answers1

0

In your code you are calling the getMovies(FEATURED_API) twice on mount (one outside the if cause and the other in the else).

useEffect(() => {

 getMovies(FEATURED_API) // first call

 if (searchTerm) {
   getMovies(SEARCH_API + searchTerm);
 } else{
  getMovies(FEATURED_API) // second call because searchTerm is an empty string
 }
}, [searchTerm])

And the other two calls are probably because you have StrictMode enabled (it is enabled as default with create-react-app) and you haven't noticed it. StrictMode mounts your component twice in development mode to help you detect problems in your code in an easier way.

You can check this post comment with a more descriptive concept of what StrictMode does.

DrunkOldDog
  • 718
  • 5
  • 12