Search code examples
reactjsexpressobjectaxiosrender

Can you render an object inside an object?


I'm not sure how I would select this data if it's possible: Console Data, I am trying to select the data within the 'posts' table, since I have relations setup for the users table & posts table

This is how I usually render the data.

    render() {
        console.log(this.state.postData);
        if (this.state.postData.length === 0) {
            return <div>Profile data not found</div>
        }

        const dashPost = this.state.postData.map(post => (
            <div key={post.UserId}>
                <h1>{post.FirstName}</h1>
            </div>
        ));

        // Jquery animations can go here

        return <div>{dashPost}</div>
    }

I am wondering if it's possible to render the post data that comes with the user.

I decided to give this a try, but I figured it wouldn't work.

{post.posts.PostTitle}

I've came across this forum: React & Axios - Get values from an object inside of an object

BUT I have no idea how to actually implement it.


Solution

  • Looking at this.state.postData from image, post.posts is an Array. Try {post.posts[0].PostTitle} to get PostTitle of posts at index 0 or use post.posts.map to render the array of posts again.

    So your code would look something like this -

    const dashPost = this.state.postData.map(post => (
       <div key={post.UserId}>
           <h1>{post.FirstName}</h1>
            {
              post.posts.map(p => {
                 <p>{p.postTitle}</p>
              })
            }
       </div>
    ));