Search code examples
reactjsreact-hooksreducersglobal-state

array reducer is concatenating. not adding to sum. context with react


component:

  const { transactions } = useContext(GlobalContext);

  const amounts = transactions.map((transaction) => transaction.amount);

  const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(2);

the total const is throwing an error, because of toFixed

without toFixed, my numbers would concatenate as strings.

how are my numbers considered strings????????

I have try converting string to numbers with Number and parseInt. it did not work.

why are the numbers concatenating as strings?

here is the global state:

import React, { createContext, useReducer } from "react";
import AppReducer from "./AppReducer";

//Initial State
const initialState = {
  transactions: [
    {
      id: 1,
      name: "Payment to Molly Sanders",
      href: "#",
      category: "expense",
      amount: "200",
      currency: "USD",
      status: "success",
      date: "July 11, 2020",
      datetime: "2020-07-11",
    },
    {
      id: 2,
      name: "Rent",
      href: "#",
      category: "expense",
      amount: "100",
      currency: "USD",
      status: "processing",
      date: "July 1, 2020",
      datetime: "2020-07-11",
    },
    {
      id: 3,
      name: "Google",
      href: "#",
      category: "income",
      amount: "500",
      currency: "USD",
      status: "success",
      date: "July 18, 2020",
      datetime: "2020-07-18",
    },
  ],
};

//Create context
export const GlobalContext = createContext(initialState);

//Provider component
export const GlobalProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AppReducer, initialState);

  return (
    <GlobalContext.Provider
      value={{
        transactions: state.transactions,
      }}>
      {children}
    </GlobalContext.Provider>
  );
};

Solution

  • Because amount is string, change it to number and it will work.

    amounts.reduce((acc, item) => (Number(acc) + Number(item)), 0).toFixed(2);