0

After setup a simple post associated user model with rails i'd like to get the post owner avatar with react but all that i get this error:

TypeError: Cannot read property 'username''avatar' etc.. of undefined

I've tried to get the associated post user on fetching the post

async getPost() {
    // this.setState({showProgress: true})

let {
  match: { params }
} = this.props;

const response = await axios
  .get(`/posts/${params.id}`, {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    credentials: "same-origin"
  })

  .then(result => {
    this.setState({
      title: result.data.post.title,
      user: result.data.post.user.username,
      user: result.data.post.user,

     url: result.data.post.user.avatar.post.url
    });
  })
  .catch(error => {
    console.error(error);
  });


}

but Still showing error on the log and the user that is filled with the post is the user_id

So, someone has any hint to spare about this?

1
  • could you show the result of console.log(result) so that it will be easy to debug. Commented Jun 5, 2019 at 4:21

1 Answer 1

3

It is because your returned data does not include user information. In your ajax call response, you cannot query as if you are in rails controller.

In your case, you should return user information together with post in your controller action.

post = Post.find(params[:id])
user = post.user
post = post.as_json
post[:user] = user.as_json

render json: { post: post }

If you need users information for multiple posts, you can use eager loading in your rails controller action

@posts = Post.includes(:user).all.map do |post|
           post_json = post.as_json
           post_json[:user] = post.user.as_json
           post_json
         end

render json: { posts: @posts }

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

1 Comment

quyetdc that's it, thank you very much for your answer!

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.