V
V
Vadim Semennikov2019-06-20 16:55:42
JavaScript
Vadim Semennikov, 2019-06-20 16:55:42

Calculate state values ​​React?

There is a state:

state = {
        productsList: [ {
      "name":"JACKET",
    "price":"10",
      "id":"4o"
    },
    {
      "name":"JACKET",
         "price":"9.9",
      "id":"4"
    },
    {
      "name":"SHOE",
          "price":"101",
      "id":"65"
    },
    {
      "name":"Enduro",
          "price":"15",
      "id":"6jy5"
    }]
    };

How to calculate sum of price values ​​in productsList? Tried:
countPrice = () => {
    let sum = 0;
            return this.state.productsList.map((product) => {
                console.log(sum);
                return sum += product.price;
            })
    }

But an error appears in the console:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-06-20
@VadimRosh

const sum = this.state.productsList.reduce((sum, n) => sum + +n.price, 0);

UPD.
You are probably trying to render the sum something like this: {this.countPrice}. And it is necessary {this.countPrice()}.
Functions, they are... In order to be called.
By the way, why do you have strings for price? Must be numbers.

K
kn1ght_t, 2019-06-20
@kn1ght_t

const sum = state.productsList.reduce((acc, product) => acc + product.price, 0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question