Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState inside of a function this is undefined

I'm new to react so I'm sure I'm missing something basic. I'm getting undefined for this, and therefore cannot read property 'setState' attempting to set state within the return of a function that calls fetch, what am I doing wrong? Note I call MyAction from an onClick and the response data is fine.

var ItemComponent = React.createClass({

    getInitialState: function() {
        return {
            the_message: "call that API!"
        };
    },

    doFetch: function() {
        var obj = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        };
        return fetch('http://localhost:1337/site/test', obj)
            .then(function(response) {
                return response.json();
            }).then(function(data) {
                return data;
            }).catch((error) => {
                console.error(error);
            });
    },

    MyAction: function() {
        this.doFetch().then(function(response){
            this.setState({
                the_message: response.message
            });
        })
    },

    render: function() {
        return (
            <div>
                <div>{this.props.title}</div><br></br>
                <div>{this.props.price}</div><br></br>
                <div onClick={this.MyAction}>{this.props.qty}</div>
            </div>
        );
    }
});
like image 881
edencorbin Avatar asked Feb 12 '17 02:02

edencorbin


People also ask

Why is my setState undefined?

The "cannot read property 'setState' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

How do you set a state inside a function?

Syntax: We can use setState() to change the state of the component directly as well as through an arrow function. Example 1: Updating single attribute. We set up our initial state value inside constructor function and create another function updateState() for updating the state.

Why we Cannot define setState () inside render () function?

In constructor , we should avoid using setState() because this is the only place we directly assign the initial state to this. state . Also, we cannot directly put it in render() either since changing state each time triggers re-rendering which calls setState() again. This will result in an infinite loop.

Can setState be used in functional component?

useState returns the current state and a function to update it. But this function updates the value in an asynchronous way. That means by calling that function, the variable is not going to change immediately.


1 Answers

Use arrow function (() => {}) which keeps the last scope (this) as it is .

MyAction: function(){
    this.doFetch().then((response) => {
        this.setState({
            the_message: response.message
        });
    });
},
like image 178
Abdennour TOUMI Avatar answered Sep 28 '22 04:09

Abdennour TOUMI