I have the following query. I am making a simple app in which products are added and these (which are objects) have a name and a price. What I am trying to do is that where I render the variable, the total of the sum appears when I add a product, instead what appears to me is: (adding with 1) 123..
It is effective that the value that appears with the click event of adding is added to me, but it shows me not a total but the history of the sum.
let i = 0;
let total = this.state.list.map((x, i) => {
let val = parseInt(x.price);
i += val;
return i;
console.log('suma ', i);
})
return(
<Container>
<Row>
<Col sm='6'>
<Form>
<FormGroup>
<Label>Producto</Label>
<Input type='text' name='product' onChange={ e => this.getData(e) } placeholder='añade un item'></Input>
</FormGroup>
<FormGroup>
<Label>Precio</Label>
<Input type='text' name='price' onChange={ e => this.getData(e) } placeholder='añade un item'></Input>
</FormGroup>
<Button className='btn btn-success' onClick={ e => this.submitData(e) } >Añadir</Button>
</Form>
</Col>
<Col sm='6' className='mt-4 border' style={{ overflowY: 'scroll', position: 'relative', height: '200px'}}>
<h4>Productos {listado.length}</h4>
<TransitionGroup>
{listado}
</TransitionGroup>
</Col>
</Row>
<Row>
<Container className='mt-4'>
{total} **aqui es donde me aparece el 123..en vez del total**
</Container>
</Row>
</Container>
);
Errors I see in your code:
i
(which I assume is where you want to accumulate your summation) defined 2 times, once withlet
and once within your anonymousmap
.(x, i)
formap
, according to the documentation , ax
is being assigned the current value of your list and fori
the index, which doesn't agree with what you're doing later in your function logic.map
returns is a list with each of the values that you have returned within the callback function that you pass tomap
. Then, since you're returning the value ofi
(which is the index of your array), you're simply assigning total to an array[1, 2, 3]
. What you really need for your problem isreduce
, where you wouldn't even need an accumulator variable.console.log
never get hit, since you make areturn
before it even gets to that line.With these indications it should be enough for you to see for yourself how to solve your problem. Cheers