Search code examples
javascriptreactjsfetch-apireact-state-management

REACT JS reset integer counter


I have this function that gets data from a service using a fetch api call and waits for the response using async and await. If the response isn't null, it loads a react component and passes the fetched data to the component, it uses react state to manage data content. Because of the wait, i had to introduce an integer counter to help me manage the react page. So the integer counter is initialized to 0 and only increments if the response from fetch call isn't null. So i keep showing a progress bar as long as the counter is 0. Once the data state changes, the integer counter is incremented and the page loads the a new react component with the fetched data.

function CheckDeliveries(){
    const [deliveries, setDeliveries] = useState(null);
    const urlAPpend = "delivery/findByCustomerId/";
    let userid = JSON.parse(localStorage.getItem("User"))["userId"];
    const httpMethod = 'GET';
    let token = localStorage.getItem("Token");
    
    console.error('RELOAD >>>>>>', reload);

    if(reload < 1){
        makeApiAuthCallsWithVariable(userid,urlAPpend,httpMethod,token).then(
            data  => {
                if (data !== null) {
                    //console.log("Api response: Data "+JSON.stringify(data));
                    setDeliveries(data);
                    reload++
                }else{
                    console.error('Response not ok', data);
                }
            }
        )
    }

    if(reload >= 1 && deliveries !== null){
        reload = 0;
        console.error('RELOAD AllDeliveryDiv >>>>>>', reload);
        return (<AllDeliveryDiv obj = {deliveries} />);
    }else if(reload >= 1 && deliveries === null){
        reload = 0;
        console.error('RELOAD MakeDeliveryDiv >>>>>>', reload);
        return (<MakeDeliveryDiv />);
    }else if(reload === 0){
        return ( <ProgressBar striped variant="primary" now={value}/>);
    }
}

My Question

  1. I have tried using a boolean state instead of integer counter but the page gets into an infinite loop whenever i update the boolean state. Is there a way i can implement this boolean state in without experiencing the infinite loop ?
  2. After i fetch the data, and reset the counter to 0. I log the value before reset and after reset and i get 1 and 0 respectively. But when i call this function again without reloading the entire page, counter value remains 1 even after i had reset it earlier. How do i resolve this?
  3. Any better way to implement this, please share.

Solution

  • It's hard to really tell what you're going for with reload, so that's why I left the whole MakeDeliveryDiv stuff out, but this would load data from your endpoint when the component is first mounted using the useEffect side effect hook:

    function CheckDeliveries() {
      const [deliveries, setDeliveries] = useState(null);
      const [loaded, setLoaded] = useState(false);
    
      React.useEffect(() => {
        const userid = JSON.parse(localStorage.getItem("User"))["userId"];
        const token = localStorage.getItem("Token");
        makeApiAuthCallsWithVariable(
          userid,
          "delivery/findByCustomerId/",
          "GET",
          token,
        ).then((data) => {
          setDeliveries(data);
          setLoaded(true);
        });
      }, []);
    
      if (!loaded) {
        return <ProgressBar striped variant="primary" now={value} />;
      }
      if (deliveries === null) {
        return <>Data not OK.</>;
      }
    
      return <AllDeliveryDiv obj={deliveries} />;
    }