Mustafa Said Helal
Mustafa Said Helal

Reputation: 174

Array inside useEffect to use in if Statement

I'm trying to use an if statement in my code where I want it to 'open' a Calendar Box if the date of today has occurred as well as for the past days of my calendar to open.

Here is my code where I'm using an useEffect to post it on loading the React Component:

  // Call on post method via axios
  useEffect(async () => {
    console.log(daysData);

    const daysDay = daysData.map((day) => day.day);

    console.log(daysDay);

    if (date + 1 >= daysDay) {
      // Url where to post
      await axios.post(`http://localhost:5001/open/chocolate`, {
        day: date,
      });

      alert('New day is available to eat!');
    }

    setOpenCalendarBox('');
  }, []);

I'm trying to get an array I've initiated a few lines above of the useEffect function (daysData) and I want the value of the 'day' item inside of the objects inside of the array and then compare the date of today if it is equal to or less than daysDay (day item inside of daysData)

Here is the code for my array:

// Here I initalize the array with useState
  const [daysData, setDaysData] = useState([]);

  // Here is the port I'm fetching my array from.
  useEffect(() => {
    fetch('http://localhost:5001/chocolates')
      .then((resp) => resp.json())
      .then((data) => setDaysData(data));
  }, []);

And here is the date code:

  // Initiate new Date
  const current = new Date();
  // Retrieve current day of the month
  const date = current.getDate();

I can't seem to get the effect I want. I basically only want to see if the day has passed or if it is today then I want it to post to '/open/chocolate'.

Upvotes: 0

Views: 100

Answers (1)

Terry
Terry

Reputation: 66123

That's probably because the value of daysData is set asynchronously, yet the useEffect block that depends on it does not list it as a dependency. Therefore you are invoking logic, which requires daysData to be populated asynchronously, when the component is loaded at runtime. So daysData will be empty.

A solution is to simply add daysData in the dependency array, so that you will only execute whatever logic that is in there once the array is successfully populated.

On the other hand, you are comparing a number against an array: which will give an unexpected result. If you want any of the day to meet date + 1, use daysDay.some(d => date + 1 >= d). If you want all of the days to meet date + 1, use daysDate.every(d => date + 1 >= d).

useEffect(async () => {
  const daysDay = daysData.map((day) => day.day);

  // This needs to be fixed, see comment for options
  if (daysDay.some(d => date + 1 > d)) {
    // Url where to post
    await axios.post(`http://localhost:5001/open/chocolate`, {
      day: date,
    });
  }

  setOpenCalendarBox('');
}, [daysData]);

Upvotes: 1

Related Questions