1
I’m starting my studies with React and needed a help: I have an application that shows a list of "solutions".
It also has a button that goes to a new page (which I programmed via Router) able to add more "solutions".
The problem is that when I add a new "solution" via setState()
, by going back to the previous page (the page showing all solutions) the state goes back to the initial state and the added solution is deleted.
I tried to research Stackoverflow in English and saw that they had a solution, which I understood is a dependency called HISTORY. But I found very little information about it, and the explanation was confused.
Follows the code that makes use of the Router and also does the setState()
:
class App extends Component {
constructor(props) {
super(props)
this.handleSave = this.handleSave.bind(this)
this.state = {
data: [
{
nome: 'Andamento',
desc: 'Quando o contrato está em andamento e pode ser alterado'
},
]
}
}
handleSave(e) {
e.preventDefault()
let nome = document.querySelector('[data-js="nome"]').value
let desc = document.querySelector('[data-js="desc"]').value
// SALVANDO O SETSTATE, TUDO CERTO!
this.setState(prevData =>({
data: [{nome: nome, desc: desc}, ...prevData.data]
}))
console.log(this.state.data)
}
render() {
return (
<div className="App">
<BrowserRouter>
<Switch>
<Route path="/" exact
render={() => <SituacoesList data={this.state.data} />} />
<Route path="/addnew" exact
render={() => <SituacaoAdd data={this.state.data}
handleSave={this.handleSave} />} />
</Switch>
</BrowserRouter>
</div>
);
}
}
The class that displays the data is a simple class that only shows the data list via .map()
, it makes no change in the this.state.data
.
If you need any more information, just ask!
Follow Github repository with full code: https://github.com/BiancaPereira/react-incidents-list
Perfect Paul, that’s right!
– Bianca Pereira