Web application with React making infinite requests

Asked

Viewed 154 times

2

export default class Usuariobox extends Component{

constructor() {
    super();
    this.state = {lista: []};
}

componentDidMount(){
  this.Listar();
}

Listar(){
  axios.get('http://localhost:8000/user').then(function(resposta){
    this.setState({lista: $(resposta.data)});
  }.bind(this));
}

render(){
    return(
        <div>
            <FormUsuario Listar={this.Listar()} />
            <TabelaUsuario lista={this.state.lista} Listar={this.Listar} />
        </div>
    );
}

}

When I go up the server the browser starts crashing and when I go to see in the network the same is doing infinite user requests in the api, I believe the error is in Formusuario Listar={this. List()} /> but don’t know how to solve. Any hints?

1 answer

1


Transform that line

<FormUsuario Listar={this.Listar()} />

in

<FormUsuario Listar={this.Listar} />

Executing the function inside the render causes a new request, which causes a setState, which causes a new render... Infinite loop. In fact, the correct one is "bindar" the method Listar in the class constructor (or use Arrow functions).

class MinhaClasse extends React.Component{
    constructor() {
        super();

        this.state = {
            lista: []
        };

        this.Listar = this.Listar.bind(this);
    }

    componentDidMount(){
      this.Listar();
    }

    Listar(){
      axios.get('http://localhost:8000/user')
        .then(function(resposta){
            this.setState({lista: resposta.data}
        ).catch((err)=> {});
    }

    render(){
        return(
            <div>
                <FormUsuario Listar={this.Listar} />
                <TabelaUsuario
                    lista={this.state.lista}
                    Listar={this.Listar}
                />
            </div>
        );
    }
}

Browser other questions tagged

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