1

I am still new to React Js and am learning. So please bear me with me if this is a foolish question. I was trying to fetch data using get request. The problem was every time useEffect was running two times on refresh page. I researched and found that this was an issue with React 18 in strict mode. So I stopped the multiple get request using ABortController. It worked.

The problem came later when I wrapped my get request code in another separate function called fetchData. Now abort controller is not cancelling my multiple request. Moreover the useEffect is running more than two times on page refresh. I tried to wrap my fetchData function in useCallback but that didn't help. I am attaching the code and screenshot of console. Please help me.

import {get} from "components/AxiosUtilities";
import {visitations_url} from "components/Urls";
import React,{useEffect,useState,useMemo} from "react";
import {useCallback} from "react";

const Visitations = ({}) => { 


const fetchData =useCallback((controller,k)=>{
    console.log(k);
            get(visitations_url,{signal:controller.signal}).then(res=>{
                            console.log("visitations",res.data);
                        })

}, [])

  


useEffect(()=>{
    const visitations_controller=new AbortController();
    fetchData(visitations_controller,2);

    return ()=>{
        visitations_controller.abort();
    }
},[fetchData])
return(<>



        <div className="w-full">

        </div>


    </Layout>

</>)
};

export default Visitations;

Console Output

JustAG33K
  • 1,403
  • 3
  • 13
  • 28

1 Answers1

0

AbortController is used to cancel an api call when the component is unmounted before the api call is completed. Not to remedy React's way of doing things. And the double render with strict mode isn't an "issue" it just happens on development. On the other hand, AbortController is the right choice here because you would want to cancel that call when user decides to go to another page or something. But your useEffect runs two times on codesandbox, and AbortController works ok.