How to use reduce() on a map() with data coming from the Firestore

Asked

Viewed 52 times

0

I have an array of data coming from the firestore. With the data received by the firestore I make a map to make the display available as a table. When I try to make a table reduce to compute the sum of all values, returns that the reduce is not a function.

Follow the data coming from the firestore:

{data: 1/1, desc: 'conta de gás', price: 138}

My map:

{viewContas && viewContas.map(vc => {
                        if(auth === vc.authorId)
                            return (
                                <tr key={vc.id}>
                                    <td>{vc.data}</td>
                                    <td>{vc.desc}</td>
                                    <td>R${vc.price}</td>
                                    <td>

I can’t use {vc.price.reduce(~~)}.

2 answers

0

Opa quiet friend?

So I guess you’re trying to use the method reduce() in a single value, using it within your map.

To be able to use the reduce() you have to use in a list, follow the example below.

let data = [
  {data: 1/1, desc: 'conta de gás', price: 138},
  {data: 1/1, desc: 'conta de gás', price: 139},
  {data: 1/1, desc: 'conta de gás', price: 140},
]

let prices = data.map( (v,i) => {
  return v.price;    
})

console.log( prices.reduce( (a,b) => {
  return a+b;
}));

0

I couldn’t get it, buddy, it’s still the same mistake... remembering that the viewContas, is where I am accessing the firestore via the Redux viewContas: state.firestore.ordered.contas

const { viewContas, auth } = this.props

        let prices = viewContas && viewContas.map((v,i)=>{
            return v.price;
        })

        console.log( prices.reduce( (a,b) => {
            return a+b;
          }))

Typeerror: Cannot read Property 'reduce' of Undefined

Browser other questions tagged

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