Home > Software design >  React - infinite loop using get request when using useState hook
React - infinite loop using get request when using useState hook

Time:09-25

New to react and working on a project. I have a component which is using a GET request from backend. all seems to work properly apart from when I try to save response data using useState() hook

whenever I try to setCompany with data I get an infinite loop while checking my console log.

without setting Company this does not happen.

I couldn't seem to find the right answer on other post's.

Component: interface GetOneCompanyProps {

    company: CompanyModel;
}

interface RouteParam {
    id: any;
}

interface CompanyById extends RouteComponentProps<RouteParam> { 

}


function GetOneCompany(props: GetOneCompanyProps): JSX.Element {

    const [id, setId] = useState('1');
    const [company, setCompany] = useState([]);
   
    const handleSubmit = (e) => {
        e.preventDefault();  
        console.log(id)
    }

    async function send() {
        
    
        try {
            const response = await axios.get<any>(globals.adminUrls.getOneCompany   id)  

                store.dispatch(oneCompanyAction(response.data) );
                console.log(response);
                const company = response.data;
                setCompany(company);

        } catch (err) {
            notify.error(err);
        }
    }

    useEffect(() => {
       
        send(); 
    });
    return (
        <div className="getOneCompany">
            <h1>hi  </h1>
            <form onSubmit={handleSubmit}>
                <label>Company ID</label>
                <input value={id} onChange={(e) => setId(e.target.value)} type="number"/>
                <input  type="submit"  value="Search "/>
            </form>

            <div>

            </div>

        </div>

    );
}

export default GetOneCompany;

I sure I am doing something wrong but cannot seem to get to it.

Thanks.

CodePudding user response:

By calling useEffect without dependencies, it'll be called on every single render cycle:

useEffect(() => {   
    send(); 
});

To execute the effect only when the component initially renders, add an empty array as dependencies:

useEffect(() => {   
    send(); 
}, []);

Update As @KausUntwale pointed out, you're using id inside your send() function. To execute send any time id changes, add id to your useEffect dependencies:

useEffect(() => {   
    send(); 
}, [id]);
  • Related