Home > front end >  What do I do when useEffect keeps fetching data after every single code change?
What do I do when useEffect keeps fetching data after every single code change?

Time:11-12

I checked my console and I noticed data was being fetched everytime my code change, I'm working with an API that has only limited accesss so this is kind of like a bum.

Fetching the data with useEffect, I included an empty dependency array so it only fetches the data once when the component is registered.

React.useEffect(()=>{
fetch('
https://api.themoviedb.org/3/discover/tv?api_key=172f725b29bb24b6e294a988fc5&language=en-         US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=16&without_genres=107,10759,99,80,35,10764,18,10751&with_watch_monetization_types=flatrate
')
    .then(res => res.json())
    .then(data => console.log(data)),
),[]}
  • I imported Home.jsx (which is the component fetching the data) into App.jsx
App.jsx
           <Router>
                <Navbar />
                <Routes>
                {/* right here is Home component being rendered*/}
                  <Route path="/" element={<Home />} />
                  <Route
                    path="/artisteMusicOverview"
                    element={<ArtisteMusicOverview />}
                  />
                </Routes>
              </SearchContext.Provider>
            </Router>

How I do work my way around this bizarre complication please?

CodePudding user response:

Mock your API call

I'm working with an API that has only limited access

Then don't fetch from that API while you are developing. Replace fetch by a mocking function returning mocked data (that you could copy from one real response of the API).

Once you are done developing, then you can replace it by a real fetch.

You could have some global switch/environment variable for switching between mock and real fetch, just make sure that your prod code will not call the mocked data.

Why is useEffect triggered?

We don't know your entire development stack so this is just a guess, but you likely have some hot reload/fast refresh mechanism that remounts your component when you save a code change.

  • Related