3

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>

1 Answer 1

11

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.