How to keep setState using Router in React?

Asked

Viewed 217 times

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". inserir a descrição da imagem aqui

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

1 answer

2


Your bug is being caused by the use of TAG <a href="/" onClick={this.props.handleSave}>Salvar</a>. Using this tag you force the page to be updated by assembling all its components again, thus losing all states that had been changed.

Using the React-router-dom it is recommended that you use the component Link that already makes all the control of your history Browse.

When you use the tag you force the page update which makes a new request by loading the files to the browser again without need. Using the Link the page is updated without requests, using the React structure to render its components again. That is, it will get much faster.

To use the Link just you inform the desired path in the same way.

import { Link } from 'react-router-dom';

// [...]

<Link to='/' onClick={this.props.handleSave}>Salvar</Link>

// [...]

  • 1

    Perfect Paul, that’s right!

Browser other questions tagged

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