Search code examples
reactjsreduxstorereducersmern

React / Redux App Issue Fetching Data from MongoDB via API


I am new to Redux and setting up an app with Campaign / Products / Users along with Posts from the MERN v2.0 boilerplate.

I have setup my app to have a fetchPosts action. My page has the following (code from bottom half)

// Actions required to provide data for this component to render in sever side.
PostListPage.need = [() => {
   return fetchPosts();
}];

// Retrieve data from store as props
function mapStateToProps(state) {
  return {
    posts: getPosts(state)
  };
}

PostListPage.contextTypes = {
  router: React.PropTypes.object,
};

export default connect(mapStateToProps)(PostListPage);

Get Posts passes the state and should add posts object to the store. I can hit the API route and see that the back-end is working and loading the JSON object as expected.

However, my app is giving me an error within the PostReducer --

// Get all posts
export const getPosts = state => state.posts.data;

The error is when I go to the route --

TypeError: Cannot read property 'data' of undefined
at getPosts (/Users/yasirhossain/Projects/showintel/client/modules/Post/PostReducer.js:31:34)
at mapStateToProps (/Users/yasirhossain/Projects/showintel/client/modules/Post/pages/PostListPage/PostListPage.js:48:12)
at Connect.configureFinalMapState (/Users/yasirhossain/Projects/showintel/node_modules/react-redux/lib/components/connect.js:155:27)

Any help is appreciated!


Solution

  • In the combineReducer file, I forgot to add PostReducer as alluded to by free_soul in the comments.

    export default combineReducers({
      app,
      posts,
    });
    

    Importing PostReducer and adding it, did the trick!