Khpalwalk
Khpalwalk

Reputation: 981

React Redux mapStateToProps loads data in the second call

mapStatToProps is callings it's self twice and loads data on the second call but then doesn't assign it to components as a prop and returns an empty array.

The Reducer:

 export default function postsReducer(state = initialState.posts, action) {
  switch (action.type) {
    case types.LOAD_POSTS_SUCCESS:
      return action.posts;
    default:
      return state;
  }
 }

Here is my mpStateToProps func:

function mapStateToProps(state, ownProps) {
     const singlePost = state.posts.filter(post => post.code == ownProps.params.id);
      return {
        post: singlePost
     };
   }

Here is my Component's state:

this.state = {
   post: [...props.post]
};

Upvotes: 0

Views: 682

Answers (1)

QoP
QoP

Reputation: 28397

Your code is probably right, but it seems like you forgot to update your state.post value when your component receives new props.

componentWillReceiveProps(nextProps) {
  this.setState({
    post: nextProps.post
  });
}

Upvotes: 1

Related Questions