Typeerror: values.reduce is not a Function

Asked

Viewed 291 times

-1

I need to sum up the values of several objects from within a list.

For this, I made a map go through my list and set that if the object has the true property it should do a reduce of all these objects and sum them up.

But at the end I come across:

TypeError: valores.reduce is not a function

How can I fix this?

import React, { Component, } from 'react'
import {Table } from 'react-bootstrap'

import {consultarExtrato} from '../../services/Extrato/index'
            
let saldo = window.localStorage.getItem('saldo');

class Teste extends Component   {
    
    

    
    constructor(props){
        super(props);

        this.state = {
            //Array que recebe os Itens da API
            transacoes: [],     
        }   
    }

    componentDidMount(){
        consultarExtrato().then(dados => this.setState({transacoes: dados}))  
    }

    
    
    render() {
        return (
            
        <div>
            {
            //Tabela com os dados
            }
           <Table striped bordered hover variant="dark">
            <tbody>
                { 
                  this.state.transacoes.map((item)  => {
                    
        
                          var valores = item.valor

                          if(item.credito){

                           function sum(acc, val){
                               return acc + val
                           }

                           let resposta = valores.reduce(sum)
                           
                            return (
                                
                            <td>{resposta}</td>
                                
                               )
                          }

                         })
                }
            </tbody>
            </Table> 
        </div>
        )
    }
    
}

export default Teste;
  • what you have inside transactions?

  • Inside transactions there is an array with several objects, this is the link to it: https://gitlab.com/desafio-conta-simples/developer/-/blob/master/mocks/transacoes.json

  • In the novic case I want to add only those that are equal to true.

  • valores.reduce(sum) is not a array! and because of the error message, it is a key to each item, that is, it is not there that makes it?

  • I’m researching a solution, not really there. Now I’m trying to map transactions, take object values, put these values inside a new array, reduce that array, and then use reduce within the reduced array. Does it work?

  • I made this Novic change, entered the values inside an array and made the reduction and then the sum, but when I print my result in the console.log, I don’t get the sum, but the values of the previous array, without being added together.

  • toquinho if you want to print the data and at the end show the sum?

  • I need to print the sum of the values of the objects that are true in the API. @novic

  • I don’t need to print the data, just show the final sum value.

Show 4 more comments

1 answer

2


You need to show the sum, then you need to do the same as Javascript does with the method reduce where your default syntax:

array.reduce(callback( acumulador, valorAtual[, index[, array]] )[, valorInicial]))

ref. Javascript Demo: Array.reduce().

Demonstrating a very simple example:

const lista = [
  {valor: 100},
  {valor: 200},
  {valor: 50},
  {valor: 110},
  {valor: 160},
  {valor: 200},
];

const soma = lista.reduce((a,b) => a + b.valor, 0);
console.log(soma);

In the code of your question that is asked by the library is as follows:

class Teste extends React.Component {
    constructor(props){
        super(props);
        this.state = {            
            transacoes: [], 
            soma: 0
        }   
    }

    componentDidMount(){
      const dados = [
      {
        "empresaId": 1,
        "dataTransacao": "2020-09-01T09:50:00",
        "valor": 5000.0,
        "finalCartao": null,
        "tipoTransacao": "TED_IN",
        "descricaoTransacao": "Transferencia recebida",
        "estabelecimento": null,
        "credito": true,
    },
    {
        "empresaId": 1,
        "dataTransacao": "2020-09-01T10:50:00",
        "valor": 5000.1,
        "finalCartao": null,
        "tipoTransacao": "SLIP_IN",
        "descricaoTransacao": "Deposito por Boleto",
        "estabelecimento": null,
        "credito": true,
    },
    {
        "empresaId": 1,
        "dataTransacao": "2020-09-01T19:50:00",
        "valor": 159.99,
        "finalCartao":"0122",
        "tipoTransacao": "CARD",
        "descricaoTransacao": "Compra com cartão de crédito",
        "estabelecimento": "FACEBOOK",
        "credito": false,
    },

      ];
      this.setState({transacoes: dados}, 
        () => this.calcularSoma(true)
      );
    }   
    calcularSoma(credito) {
      const soma = this.state.transacoes
        .reduce((a,b) => {
          if (b.credito === credito) {
            return a + b.valor
          }
          return a;
        }, 0);
      this.setState({soma});
    }
    render() {
        return (            
          <div>Soma: {this.state.soma}</div>
        )
    }    
}

ReactDOM.render( <Teste/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

When setting the state to transacoes a function was created to update the state of the sum variable as of the excerpt below:

this.setState({transacoes: dados}, 
    () => this.calcularSoma(true) // executado depois de atualizar transacoes
);

and in the method calcularSoma with parameter credito for verdadeiro or falso with reduce:

calcularSoma(credito) {
  const soma = this.state.transacoes
    .reduce((a,b) => {
      if (b.credito === credito) {
        return a + b.valor
      }
      return a;
    }, 0);
  this.setState({soma});
}

this example is that you must adapt to your code.

  • 1

    Thanks Novic! It worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.