Ad

Setting State From Axios Response And Using It In Render

- 1 answer

I have this current situation in react where the state is not getting set and if set cannot be used in render.

componentDidMount() {
    axios.get(`url`)
        .then(function(response){
            const test = response.data;
            this.setState({
                data:test
            });
        }.bind(this));
      setTimeout(function test(){
          console.log('filterdata',this.state.data);
      },2000);
}

This is my sample code that I have been trying to use but the problem here is even though I am setting the state the global this does not contain the value. I have done bind to prevent the same. I have tried two other things as well

componentDidMount() {



    axios.get(`url`)
        .then((response)=>{
            this.setState({
                data:response.data
            });


});
      setTimeout(function test(){
          console.log('filterdata',this.state.data.templateFields);

      },6000);
}

as well as this

componentDidMount() {

    var self = this;

    axios.get(`url`)
        .then(function demo(response){
            self.setState({
                data:response.data
            });


});
      setTimeout(function test(){
          console.log('filterdata',self.state.data.templateFields);
      },6000);
}

The last one has the value in self but cannot be used in render where I am using "this" like this

<ul className="filter-options">
                            {
                                this.state.data.map(function(val){
                                <p>{val.templateFields}</p>

                            }, this)

Is it really that difficult in react to get a simple promise and use it?Is there a better way to do it that I might not know about?

Ad

Answer

First thing, always use arrow functions instead of classic function declaration so you have this context passed along automatically.

Regarding your console.log do not try to log the state after you set it in componentDidMount the setState, and you request, are asynchronous.

You should always log the state in the render, or sometimes maybe in the componentDidUpdate eventually.

Take a look at this, this should work:

componentDidMount() {
    axios.get(`http://nextgen-bcs-dev-1008264651.ap-south-1.elb.amazonaws.com/templateConfig/site6/VAULT`)
        .then((response) => {
            this.setState({
                data: response.data
            });
        }).catch((error) => {
            console.error(error);
        });
}

render () {
    console.log(this.state.data)
    return (
        <ul className="filter-options">
            {
                this.state.data.map((val) => {
                    <p>{val.templateFields}</p>
                })
            }
        </ul>
    );
}

If it doesn't, then your issue is somewhere else.

Ad
source: stackoverflow.com
Ad