Create a <div> inside a . catch in Aces

Asked

Viewed 68 times

3

Hello, I am currently developing in React and am trying to put a div inside the .catch. I am currently using the following code:

  componentDidMount() {
axios.get(API_ListaEmpresa)
  .then(response => {
    this.setState({ lista: response.data });
    console.log(response.message)
  })
  .catch(error => {
    alert('Teste');
  })
}

Instead of

alert('Teste');

I would like to place the following code:

    <div>
  <Alert variant="warning">
    <Alert.Heading>ERRO!</Alert.Heading>
    <p>
      Houve um erro na hora de carregar a lista de empresas. Iremos tentar novemente recarregando a página.
      Clique em Recarregar para Recarregar a página ou clique em Cancelar para permanecer na página.
    </p>
    <hr />
    <div>Erro!!!</div>
    <hr />
    <div className="d-flex justify-content-end">
      <Button variant="outline-success">
        Recarregar
      </Button>
    </div>
  </Alert>
</div>

How should I do it?

1 answer

4


The correct way is not to put a div inside the catch, but to change the state for this div to be shown...

So no catch usa:

componentDidMount() {
    axios.get(API_ListaEmpresa)
      .then(response => {
        this.setState({ lista: response.data });
        console.log(response.message)
      })
      .catch(error => {
        this.setState({showError: true});
      })
}

and somewhere in the render() you must have logic to show a component (in case of error) or div with the error (in case of error);

render() {
    return this.state.showError ? <ErrorComponent> : <NormalFlowComponent>;
}
  • Would it be possible to make the surrender but without using the logic part? This Alert I want to give you will only be called when you have an error, because of this reason I just wanted to render the <div>. It would be possible?

  • @Gabriel React’s idea is to make the UI an expression of state, that is prepares the components that exist and can ever be shown and then the state is who decides what should be shown or not. The idea of "creating a div within catch" is a way of thinking more related to previous generations of Javascript like jQuery. Create the UI as a function of the state and you will see that you start to think differently. It makes sense?

Browser other questions tagged

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