0

I'm working with react and trying to push elements to an array on my state using the click of a button. The issue is that I never get it the right way:

Lets say, I have the empty array and I push the numbers 1, 2, 3 in this order.

If I console log the array on the button press, I get: [], [1], [1,2]. It seems like it is always one input behind. So from what I see it means that the first time my element is rendered, the array is empty and that's why I get this result, but I don't see how to solve it.

Here is my code (the data to add to the array comes from other component):

import React from 'react';
import {Component} from 'react';

import 'bulma/css/bulma.css'
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            colecoesSelecionadas: []
        };
    }
    adicionarColecaoSelecionada(colecao) {
        this.setState({colecoesSelecionadas: [...this.state.colecoesSelecionadas, colecao]});
        console.log(this.state.colecoesSelecionadas);
    }
    render() {
        return (
                <section>
                    <Options>
                        <TabsArea
                            addColecao ={this.adicionarColecaoSelecionada.bind(this)}/>
                    </Options>
                </section>
            </div>
        )
            ;
    }
}

export default App;
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Nelson Silva
  • 429
  • 7
  • 22
  • setState is asynchronous, so, you have to put your console.log inside the callback of the setState method: this.setState({colecoesSelecionadas: [...this.state.colecoesSelecionadas, colecao]},()=>{console.log(this.state.colecoesSelecionadas)}); – benjamin Rampon Mar 29 '18 at 15:30
  • its because setState is async, use callback method to check the updated state value, Like this: `this.setState({....}, () => {console.log(this.state)})` – Mayank Shukla Mar 29 '18 at 15:30
  • awesome, thanks you and sorry for the duplicated. either way, its safe to say that my state is updated with the values, right ? Also, I need to know when I have 4 elements inside the array, can I make the verification after the setstate ? For what I'm checking, it only triggers when I have 5... – Nelson Silva Mar 29 '18 at 15:33

0 Answers0