最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calculate sum of values in state with React Hooks - Stack Overflow

programmeradmin7浏览0评论

I'm using React Hooks to store datas in the state. I would like to create a function that calculate the sum of the values. I tried something but it is not working.

Here is my ponent with the function "totalIne" :

import { UidContext } from "../ponents/AppContext"
import React, { useContext, useEffect, useState } from "react"
import axios from "axios"

export default function Balance() {
    const uid = useContext(UidContext)
    const [userWalletInes, setUserWalletInes] = useState('')
    const [userWalletFees, setUserWalletFees] = useState('')
    const [formInes, setformInes] = useState(false)

    useEffect(() => {
        if (uid !== null) {
            axios.get(`${process.env.REACT_APP_API_URL}api/balance/${uid}`)
                .then((res) => {
                    setUserWalletInes(res.data[0].ines)
                    setUserWalletFees(res.data[0].fees)
                })
        }
    }, [uid])

    const totalIne = () => {
        Object.entries(userWalletInes).map(([key, value]) => {
            let total = 0
            console.log(value)
            for (let i = 0; i < value.length; i++) {
                total += value[i]
            }
            return total
        })
    }

    return (
            <section className="border my-2 w-max md:w-11/12 mx-auto text-center">
                <h1 className="text-3xl my-5">Solde</h1>
                <div className="text-left mx-auto flex">
                    <p className="w-32 border p-1">Montant des revenus</p>
                    <p className="w-32 border p-1">{totalIne()}</p>
                </div>
            </section>
    )
}

The console.log(value) returns :

1500 Balance.js:42 
640 Balance.js:42 
90 Balance.js:42 
1500 Balance.js:42 
640 Balance.js:42 
90 Balance.js:42

Any idea ? Thank you

I'm using React Hooks to store datas in the state. I would like to create a function that calculate the sum of the values. I tried something but it is not working.

Here is my ponent with the function "totalIne" :

import { UidContext } from "../ponents/AppContext"
import React, { useContext, useEffect, useState } from "react"
import axios from "axios"

export default function Balance() {
    const uid = useContext(UidContext)
    const [userWalletInes, setUserWalletInes] = useState('')
    const [userWalletFees, setUserWalletFees] = useState('')
    const [formInes, setformInes] = useState(false)

    useEffect(() => {
        if (uid !== null) {
            axios.get(`${process.env.REACT_APP_API_URL}api/balance/${uid}`)
                .then((res) => {
                    setUserWalletInes(res.data[0].ines)
                    setUserWalletFees(res.data[0].fees)
                })
        }
    }, [uid])

    const totalIne = () => {
        Object.entries(userWalletInes).map(([key, value]) => {
            let total = 0
            console.log(value)
            for (let i = 0; i < value.length; i++) {
                total += value[i]
            }
            return total
        })
    }

    return (
            <section className="border my-2 w-max md:w-11/12 mx-auto text-center">
                <h1 className="text-3xl my-5">Solde</h1>
                <div className="text-left mx-auto flex">
                    <p className="w-32 border p-1">Montant des revenus</p>
                    <p className="w-32 border p-1">{totalIne()}</p>
                </div>
            </section>
    )
}

The console.log(value) returns :

1500 Balance.js:42 
640 Balance.js:42 
90 Balance.js:42 
1500 Balance.js:42 
640 Balance.js:42 
90 Balance.js:42

Any idea ? Thank you

Share Improve this question edited Jun 28, 2021 at 15:52 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Jun 22, 2021 at 8:21 user14265379user14265379
Add a ment  | 

2 Answers 2

Reset to default 5

It seems you are close. You are logging the value and it's clearly not an array, so there is no length property and you can't iterate over it.

I would suggest using an array.reduce over the object's values and sum them with a puted total.

const totalIne = () => {
  return Object.values(userWalletInes).reduce((total, value) => total + value, 0)
}

Other than this, you need to provide valid initial state for userWalletInes, i.e. it needs to be an object instead of an empty string. This is so the totalIne function can work correctly with the initial state until the data is fetched and/or updated.

const [userWalletInes, setUserWalletInes] = useState({});

From what your logs are showing, I'd expect the function to work like this:

const totalIne = () => {
    let total = 0
    Object.entries(userWalletInes).forEach(([key, value]) => {
        total += value
    })
    return total
}
发布评论

评论列表(0)

  1. 暂无评论