Search code examples
reactjsapireact-hooksaxiosuse-effect

why is my page reloading when re rendering a component


I am doing a api call and then another for each of the object received in the first request.

I have a load more button at the end of my page to get more data added on the page.

Each time the button is clicked the data is fetched but the page reloads and then makes the UI go back to the top of the page instead of just appending the new data.

Not sure what would force the page to reload?

This is my useEffect hook:

useEffect(() => {
    //this if/else statement is to find out if the page has been reloaded
    if (performance.navigation.type === 1) {
      console.log("This page is reloaded");
    } else {
      console.log("This page is not reloaded");
    }
    setLoading(true);
    let cancel;
    axios
      .get(currentPageUrl, {
        cancelToken: new axios.CancelToken((c) => (cancel = c)),
      }).then((res) => {
        setLoading(false);
        setNextpageUrl(res.data.next);
        setPokemons([...pokemons, ...res.data.results])
      
      }).catch((e) => {
        setErr(true)
      })
  }, [currentPageUrl]);

this is the function that would change the currentPageUrl :

  const handleClick = () => {
    setCurrentPageUrl(nextPageUrl);
  }

Solution

  • After a lot of trial and error, the solution was simply to create a function that would handle the logic then put it inside the use effect.

    const request = () => {
      if (performance.navigation.type === 1) {
        console.log("This page is reloaded");
      } else {
        console.log("This page is not reloaded");
      }
      setLoading(true);
      let cancel;
      axios
        .get(currentPageUrl, {
          cancelToken: new axios.CancelToken((c) => (cancel = c)),
        }).then((res) => {
          setLoading(false);
          setNextpageUrl(res.data.next);
          setPokemons([...pokemons, ...res.data.results])  
        }).catch((e) => {
          setErr(true)
        })
    }
    
    useEffect(() => {
      request()
    }, [currentPageUrl])