soccerway
soccerway

Reputation: 11961

How do we check the boolean value in useEffect in react hooks?

I have received the boolean value and set to setNomStatus, but how can I check if that is true to show setShowCalender(true) ?

const [nomStatus, setNomStatus] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      const email = localStorage.getItem("loginEmail");
      try {
        const res = await Axios.get(
          "http://localhost:8000/service/activeStatus", {email}
        );
        setNomStatus(res.data[0].status);
        console.log("Get status data :" + res.data[0].status);
        if(nomStatus == true){
          setShowCalender(true);
        }
      } catch (e) {
        console.log(e);
      }
    };
    fetchData();
  }, []);

enter image description here

Upvotes: 3

Views: 2913

Answers (2)

Drew Reese
Drew Reese

Reputation: 202667

You can't since React state updates are asynchronously processed, the nomStatus state update won't be available until the next render cycle. Use the res.data[0].status value to set the showCalendar state.

const [nomStatus, setNomStatus] = useState(false);

useEffect(() => {
  const fetchData = async () => {
    const email = localStorage.getItem("loginEmail");
    try {
      const res = await Axios.get(
        "http://localhost:8000/service/activeStatus",
        {email}
      );
      setNomStatus(res.data[0].status);
      console.log("Get status data :" + res.data[0].status);
      if (res.data[0].status){
        setShowCalender(true);
      }
    } catch (e) {
      console.log(e);
    }
  };
  fetchData();
}, []);

Or you can use a second useEffect hook with a dependency on nomStatus state update to set the showCalendar state.

useEffect(() => {
  const fetchData = async () => {
    const email = localStorage.getItem("loginEmail");
    try {
      const res = await Axios.get(
        "http://localhost:8000/service/activeStatus",
        {email}
      );
      setNomStatus(res.data[0].status);
      console.log("Get status data :" + res.data[0].status);
    } catch (e) {
      console.log(e);
    }
  };
  fetchData();
}, []);

useEffect(() => {
  if (nomStatus){
    setShowCalender(true);
  }
}, [nomStatus]);

Upvotes: 1

Shyam
Shyam

Reputation: 5497

You can add another useEffect which watches this change, useEffect takes a second argument which is dependency array and the effect gets called if any of the dependency array value changes .

In this case since you need to make a decision based on the nomStatus, you can add it as a dependency to your useEffect

useEffect(() => {
  if (nomStatus) {
    setShowCalender(true);
  }
}, [nomStatus]);

Upvotes: 1

Related Questions