1

I have tried using ajax call to get data from rails to react but the state was not updating. When I tried to call state it's giving me an error that it is undefined. I have referred other questions in stack overflow but couldn't solve my problem. Here is my my ajax request.

fetchData: function(){
      $.ajax({
        url: '/orders',
        dataType: 'json',
        type: 'GET',
        success: function(result) {
          this.setState({orders: result});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    }

Click this link to view the error

<p><button  onClick={this.fetchData}>Filter</button></p>
            <div>
              {
                Object.keys(this.state.orders).map(function(key){
                  return <div key={ key }>{this.state.orders[key]}</div>
                }, this)
              }
            </div>
2
  • Please provide some more details about your react components and error which you are getting Commented Dec 26, 2016 at 13:39
  • undefined error may mean null or incorrect json return Commented Dec 26, 2016 at 13:48

2 Answers 2

1

You are trying to render the order object as a string. React doesn't like that. Try only rendering a value, not the whole order object, for example like this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { orders: {
      first: { id: 311, name: 'Eric' },
      second: { id: 420, name: 'Andre' },
    }};
  }
  render() {
    return(
      <div>
      {
        Object.keys(this.state.orders).map(function(key){
          return <div key={ key }>{this.state.orders[key].id}</div>
        }, this)
      }
      </div>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>

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

Comments

0

The error says that you are trying to render something that is an object, which is not possible. The problem can be found here:

return <div key={ key }>{this.state.orders[key]}</div>

If you want to render this, then this.state.orders[key] should be either a JSX element or a value (a string for example), and it doesn't seem to be the case. I don't know what do you assign to orders with this.setState({orders: result});. If you show us the value of result we might be able to help more, but right now the problem is that this.state.orders[key] is an object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.