A
A
Alexander Isaev2017-03-27 00:49:22
Ruby on Rails
Alexander Isaev, 2017-03-27 00:49:22

How to bind Ruby on Rails models to ReactJS?

Hello! In general, I create a project on rails. For the client side I use React JS. On the users/show page, I create posts, and the Post model has a belongs_to relationship to User. I need to display the name of the post author (post.user.name) and React in the Post component does not display this. How to do this in ReactJs if he knows nothing about the relationship between the User and Post models?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2017-03-30
@IsaevAlex

In react applications, the redux library is used to store data, the requests themselves must be made in actions (action), in order to deal with asynchrony and make requests correctly, use redux-thunk or redux-api-middleware, if in the body of the response from the server you do not receive the data that you need, then this is a problem on the server. You should have an endpoint /api/user/:id where you can get the user, and the user object should have post_id with the post id, and you could get it for example on /api/post/:id, but if you need to do do it quickly without redax and fetch data in ComponentDidMout via fetch, in es6 there will be something like this

constructor(props) {
  super(props);
  this.state = {
    post: {
      user: {}
    }
  }
}
ComponentDidMount() {
  const { postID } = this.props;
  let data = fetch('localhost:3000/post/' + postID)
    .then((response) => { 
      this.setState({post: JSON.stringify(response.json)}, (prevState) => {
        fetch('localhost:3000/user/' + prevState.post.user_id)
        .then ((response) => {
          this.setState({ ...prevState, user:  JSON.stringify(response.json)});
        });
      });
    });
}
render () {
  return (
    <div>
      {this.state.post.user.name}
    </div>
  )
}

it should also be noted that the server must have CORS permission for this client

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question