Friday 2 October 2020

How to add array to useState array after component mount React

I have updated this question.

I can't figure out why the setDailyTotals useState Hook is not being called at the end of the CalculateTotals function. setDailyTotals appears to be called when the component mounts but never gets called again after that.

Basically What I am trying to do is sum up of the field values i.e numberOfAdults, numberOfKids, moneyIn for each day and display each day tta

Sorry If I'm missing something simple and I would really appreciate any help, Thank you.

export const TabBar = () => {
  const [selectedTab, setSelectedTab] = useState(0);
  const forms = GetForms();
  const [dailyTotals, setDailyTotals] = useState([]);
  debugger;

  useEffect(() => {
    debugger;
    if (forms.length !== 0) {
      CalculateTotals();
    }
  }, [forms]);

  const CalculateTotals = () => {
    //This Function is used to calculate how many adults, kids were in on a given day
    //It will also calculate the total money taken in for each day too.

    let totalNumberOfAdults = 0;
    let totalNumberOfChildren = 0;
    let totalMoneyIn = 0;
    let selectedFormDate = moment().format("llll");
    let dayTotal = {};
    let totals = [];

    debugger;

    forms.forEach(form => {
      if (moment(form.timeIn).isSame(selectedFormDate, "day")) {
        // if the date on the form is the same as the selectedFormDate
        // Then add the below counts from the form to a local count variable.

        // repeat this process until the form date does not match the selected form date
        // which then indicates, the loop is iterating over a different day.
        // when that happens, else will be triggered.
        totalNumberOfAdults += parseInt(form.numberOfAdults || 0);
        totalNumberOfChildren += form.children.length || 0;
        totalMoneyIn += form.totalGroupPrice || 0;
      } else {
        // when the loop has started iterating over a different day
        // take the local count variables i.e totalNumberOfAdults etc, add them to an Object
        // add that object to an array called Daily totals then reset all the local variables

        dayTotal = {
          date: selectedFormDate,
          totalNumberOfAdults,
          totalNumberOfChildren,
          totalMoneyIn
        };
        totalNumberOfAdults = 0;
        totalNumberOfChildren = 0;
        totalMoneyIn = 0;

        if (dayTotal.totalNumberOfChildren !== 0) {
          //Todo figure out how to push new item to use state array

          // setDailyTotals(dailyTotals => [...dailyTotals, dayTotal]);
          // setDailyTotals(prevState => ({ prevState, dayTotal }));
          totals.push(dayTotal);
          dayTotal = {};
        }

        // after adding object to array, reset counts, its important to add
        // totals for the currently iterated day to local counts again, to continue the tally.
        totalNumberOfAdults += parseInt(form.numberOfAdults || 0);
        totalNumberOfChildren += form.children.length || 0;
        totalMoneyIn += form.totalGroupPrice || 0;

        // now that the form date is no longer the same as the selectedFormDate
        // selectedFormDate must be changed to match the now current form Date
        selectedFormDate = moment(form.timeIn);

        console.log("totals: ", dailyTotals);
      }
    });
    // at the end of the loop, when all of the forms have been iterated
    // close off, and add the final day to the object and add to array.
    dayTotal = {
      date: selectedFormDate,
      totalNumberOfAdults,
      totalNumberOfChildren,
      totalMoneyIn
    };
    totalNumberOfAdults = 0;
    totalNumberOfChildren = 0;
    totalMoneyIn = 0;
    
    
    totals.push(dayTotal);
    dayTotal = {};
    console.log("totals 2:", totals);
    
    

    //State Array
    setDailyTotals(totals);
    console.log("dailyTotalsStateArray: ", dailyTotals);
  };

if (forms.length === 0)
    return (
      <div>
        <h2>No Records</h2>
      </div>
    );

  return (
    <>
      <Paper>
        <Tabs
          value={setSelectedTab}
          onChange={handleChange}
          indicatorColor={"primary"}
          textColor={"primary"}>
          <Tab label={"Records"} />
          <Tab label={"Totals"} />
        </Tabs>
      </Paper>

      {selectedTab === 0 && <RecordTable forms={forms} />}
      {selectedTab === 1 && <TotalsCountTable forms={dailyTotals} />}
    </>
  );
};

Console.log output



from How to add array to useState array after component mount React

No comments:

Post a Comment