Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Uncaught TypeError: this.setState is not a function

This is my first React code. I am trying to call a Restful web services from React. It kept saying "Uncaught TypeError: this.setState is not a function". I couldn't figure out what's wrong with the code.

<!DOCTYPE html>
<html>
    <head>
        <title>React Flux</title>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="component"></div>

        <script type="text/jsx">

            var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/rest/user/456"
                    }).then(function(data) {
                        this.setState({text: data.name});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });

            React.render(<JavaEEWSTest />, document.getElementById('component'));
        </script>
    </body>
</html>
like image 348
johnsam Avatar asked Feb 10 '26 17:02

johnsam


1 Answers

You need set this to callback function

$.ajax({
  url: "http://localhost:8080/rest/user/456"
}).then(function(data) {
 this.setState({text: data.name});
}.bind(this))
^^^^^^^^^^^

but not for $.ajax/then - }).bind(this)

like image 114
Oleksandr T. Avatar answered Feb 13 '26 12:02

Oleksandr T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!