Having trouble fetching data inside useEffect due to useNavigate hook

Viewed 35

I'm getting a warning in the browser that says "You should call navigate() in a React.useEffect(), not when your component is first rendered.". I am also getting an error that some of the data that my API which is theMovieDb isn't loading. I am calling the api here in useEffect.

useEffect(() => {
  getMovieData(sort, genreId, monetization, page)
    .then(res => setMovieData(res.data))
    .catch(err => console.log(err));
}, [sort, monetization, genreId, page]);

The parameters inside the MovieData function are urlParams. In addition to the params I've also declared the useNavigate hook as well as the movieData state hook.

let { genreId = "default" } = useParams();
let { sort = "popularity.desc" } = useParams();
let { monetization = "flatrate" } = useParams();
let { page = "1" } = useParams();
let navigate = useNavigate();
const [movieData, setMovieData] = useState<MovieData>({
    results: [], total_pages: 0

I am calling the navigate function inside a sidebar component.

<Sidebar
  genre={genreId}
  sort={sort}
  monetization={monetization}
  filterByGenre={(genreNum: string) => {
    navigate(`/${genreNum}/${monetization}/${sort}/${page}`);
  }}
  filterByMonetization={(monetizationType: string) => {
    navigate(`/${genreId}/${monetizationType}/${sort}/${page}`);
  }}
  sortBy={(sortBy: string) => {
    navigate(`/${genreId}/${monetization}/${sortBy}/${page}`);
  }}
/>

As well as a footer pagination component

<PageSort
  pageNum={parseInt(page)}
  total_pages={movieData.total_pages}
  pagination={(page: number) => {
    navigate(`/${genreId}/${monetization}/${sort}/${page}`);
  }}
/>

So my question is why I am getting the warning in the console and how am I supposed to use the navigate hook? I've read that the solution is to use navigate inside useEffect, but I don't know how that solves my problem and I don't see that in the documentation.

0 Answers
Related