Jenil Chavda
Jenil Chavda

Reputation: 93

IF Else statement not properly worked in setInterval() function

I have a problem with accessing if else, if else can called but both block called if block as well as else block at a same time

so how can i make proper working if else block

my code is

const UserCard=(props)=>{


const[LiveOrdStatus,setStatus] = useState();
const[order_ID,setordid] = useState(props.orderId);

const labels=["Order","Confirm","Ready","Deliver","Delivred"];
let number = 0;

function LiveFetchData(){
   fetch('https://example.in/app/live_update.php', {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        'S_KEY':'84014',
        'order_id':order_ID,
      })
    }).then((response) => response.json())
    .then((json) => {
      setStatus(json.order_status);
      //console.log(json.order_status);
    }).catch((err) => { console.log(err); });
}

LiveFetchData();
   setInterval(() => {
        if(LiveOrdStatus==="DELIVERED")
        {
         console.log("its okk :"+LiveOrdStatus);
        }else{
         console.log("not called :");
        }
  }, 10000);

 }

my output is enter image description here

Upvotes: 2

Views: 806

Answers (3)

Drew Reese
Drew Reese

Reputation: 202676

You are calling and setting an interval each render cycle and from what I can tell you never clear any intervals. You likely only want to start one interval when the component mounts. Don't forget to return a cleanup function to clear any running intervals when the component unmounts.

useEffect(() => {
  const timerRef = setInterval(() => {
    if (LiveOrdStatus === "DELIVERED") {
      console.log("its okk :", LiveOrdStatus);
    } else {
      console.log("not called :");
    }
  }, 10000);

  return () => clearInterval(timerRef);
}, []);

You are also calling LiveFetchData(); directly in the function body, which will cause render looping since it also updates state. I'm not sure when you want this function to be called, but it's likely that you also want to place it into an useEffect hook.

useEffect(() => LiveFetchData(), []);

This will invoke it once when the component mounts, but if you need to call it more often then you should figure out what any dependencies are or add additional interval timers, etc...

Update

I am facing one more problem , when accessing LiveOrdStatus inside else than it show " not called : undefined "

Yeah, I see how that can happen now. Basically the initial LiveOrdStatus is closed over in the setInterval callback scope.

Use a React ref to cache the current LiveOrdStatus state value and access that in the interval.

    const LiveOrdStatusRef = React.useRef();

    useEffect(() => {
      LiveOrdStatusRef.current = LiveOrdStatus;
    }, [LiveOrdStatus]);

    useEffect(() => {
      const timerRef = setInterval(() => {
        if (LiveOrdStatus === "DELIVERED") {
          console.log("its okk :", LiveOrdStatusRef.current);
        } else {
          console.log("not called :", LiveOrdStatusRef.current);
        }
      }, 10000);

      return () => clearInterval(timerRef);
    }, []);

Upvotes: 2

Sifat Amin
Sifat Amin

Reputation: 1186

From my understanding, you're fetching LiveFetchData(), one time only when the userCard Component mounts. So you can wrap call it inside the useEffect()

useEffect(()=>{
 LiveFetchData(); // it will populate the status first
},[])

Then you can call setInterval normally to check the status.

Upvotes: 0

sazzad
sazzad

Reputation: 525

you should call the function which are causing side effect in useEffect hook.

   const LiveFetchData = () => {

     fetch('https://example.in/app/live_update.php', {
     method: 'POST',
     mode: 'no-cors',
     headers: {
      'Content-Type': 'application/json',
     },
     body: JSON.stringify({
     'S_KEY':'84014',
     'order_id':order_ID,
    })
    }).then((response) => response.json())
    .then((json) => {
    setStatus(json.order_status);
    //console.log(json.order_status);
    }).catch((err) => { console.log(err); });
   }
  
   useEffect(() => {
      LiveFetchData();
    } , [])

  useEffect(() => {
    const timerRef = setInterval(() => {

    if (LiveOrdStatus==="DELIVERED") {
      console.log("its okk :"+LiveOrdStatus);
    } else {
      console.log("not called :");
    }
   }, 10000);

   return () => clearInterval(timerRef);
  }, []);

Upvotes: 0

Related Questions