bounty bounty - 4 months ago 15
React JSX Question

Cannot figure out why data won't load into React component

Here is my store:

import helper from './../../helpers/RestHelpers.js';

var posts = [];

class PostStore {

constructor() {
helper.get('/api/posts')
.then((data) => {
posts = data;
console.log(posts);
}
);
}

getPosts() {
return posts;
}

};

export default new PostStore();


When I
console.log
posts from within the helper function, I get the correct data. But when I
console.log
from the component, the array of posts is empty.

Here is my component:

import React from 'react';

import postStore from '../stores/PostStore';

class Home extends React.Component {

constructor() {
super();
this.state = {
posts: postStore.getPosts()
}
console.log(this.state.posts);
}

render() {
return (
<div className="welcome">
{this.state.posts.map(function(post, index) {
return (
<PostItem post={post} key={"post " + index} />
)
})
}
</div>
)
}
}

class PostItem extends React.Component {
render() {
return <div>{this.props.post.postName}</div>;
}
}

export default Home;

Answer

I wouldn't use your PostStore as-is. Instead just use your helper directly like so:

import React from 'react';
// import your helper!

class Home extends React.Component {

    componentDidMount() {
      helper.get('/api/posts').then((data) => {
        this.setState({posts: data})
      });
    }

    render() {
        return (
            <div className="welcome">
              {this.state.posts.map((post, idx) => <PostItem post={post} key={"post " + idx} />)}
            </div>
        )
    }
}