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;