0
import React from "react";
import { useContext } from "react";
import styled from "styled-components";
import { GlobalContext } from "../context/GlobalState";
import IncomeTransactions from "./IncomeTrasactions";

function Head() {

In this part, I draw a month and a year

  let months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];
  let mY = new Date();
  let monthName = months[mY.getMonth()];
  const current = new Date();
  const date = `${current.getFullYear()}`;
  const { incomeTransactions, expenseTransactions } = useContext(GlobalContext);

  const incomeAmounts = incomeTransactions.map(
    (incomeTransaction) => incomeTransaction.incomeAmount
  );
  const expenseAmounts = expenseTransactions.map(
    (expenseTransaction) => expenseTransaction.expenseAmount
  );

In this section, I get an error "expenseAmounts.reduce(...).toFixed is not function"

const totalIncome = incomeAmounts
    .reduce((acc, item) => (acc += item), 0)
    .toFixed(2);

  const totalExpense = expenseAmounts
    .reduce((acc, item) => (acc += item), 0)
    .toFixed(2);

The code below is ok and everything works, the problem is somewhere I marked it return ( Available Budget in {monthName} {date}

{totalIncome - totalExpense}.00

Income
            <div>+ {totalIncome}</div>
          </div>
          <div className="expenses-top mt-3">
            <div>Expenses</div>

            <div>- {totalExpense}</div>
          </div>
        </BlockHeader>

        <ImageHeader src="/img/header-budget.png" />
      </Wrap>
    </div>
  );
}

export default Head;
  • What is returning from incomeAmounts .reduce((acc, item) => (acc += item), 0)? – kingan Mar 12 '22 at 13:28
  • 1
    The most likely explanation is that the elements in `incomeAmounts` and/or `expenseAmounts` are not numbers (most likely strings). The code `["1", "2"].reduce((a, b) => a + b, 0)` produces the string `"012"`, not the number `3`, because when you do `string + number`, the result is string. – T.J. Crowder Mar 12 '22 at 13:28
  • 2
    **By far**, the best way to figure out what's going on in this sort of situation is to use the debugger built into your IDE and/or browser: Set a breakpoint in the code, run the code, and when the breakpoint is reached, look at the variables and such. More [here](https://stackoverflow.com/questions/25385173/) and [here](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – T.J. Crowder Mar 12 '22 at 13:29
  • Because toFixed is `Number.prototype.toFixed`. `acc += +item` should fix the error. – naveen Mar 12 '22 at 13:34
  • Guys thank you for your effort to help me. @naveen your method works, thanks a lot! – Лука Траиловић Mar 12 '22 at 13:59

0 Answers0