Jay Ar Viluan
Jay Ar Viluan

Reputation: 59

React-Redux: Cannot read property 'map' of undefined when deleting an item

I have an error after clicking the delete button saying:

Cannot read property 'map' of undefined.

I'm new in React Redux JS.

Please see my code below of my component reducers and actions:

Post.js

class Post extends Component {
  constructor(){
    super();
    this.deletePost = this.deletePost.bind(this);
  }

  deletePost(postId){
    this.props.deletePost(postId);
  }

  render(){
    const postItems = this.props.posts.map(post => (
        <div key={post.id} className="row">
            <div className="container">
                <h3>{post.title}</h3>
                <p>{post.body}</p>
                <button
                    onClick={() =>this.deletePost(post.id)}
                    className="btn btn-danger">
                    Delete
                </button>
            </div>
        </div>  
    ))

    const divStyle = {
        padding: '15px',
    }

    return (
        <div style={divStyle}>
            <PostForm />
            <hr/>
            {postItems}
        </div>
    )
  }
}
const mapStateToProps = state => ({
    posts: state.posts.items,
    newPost: state.posts.item
}) 

export default connect(mapStateToProps, { fetchPosts, deletePost })(Post);

PostAction.js (Here is my delete action. I am using jsonplaceholder API post.)

export const deletePost = (postId) => dispatch => {
   fetch('https://jsonplaceholder.typicode.com/posts/'+postId, {
    method: 'DELETE',
  })
  .then(dispatch({
    type: DELETE_POST,
    payload: postId
  }));
}

PostReducer.js (This is my reducer.)

case DELETE_POST:{
     const newState = Object.assign([], state);`enter code here`

     const filteredItems = newState.items.filter(items => {
          return items.id != action.payload;
     });

     return filteredItems;
}

Upvotes: 0

Views: 494

Answers (2)

Gerardo Perrucci
Gerardo Perrucci

Reputation: 734

case DELETE_POST:{
 const { items } = state;
 const filteredItems = items.filter(items => {
      return items.id != action.payload;
 });

 return { 
    ...state,
    items: [ ...filteredItems ]
 };

}

Upvotes: 1

Jay Ar Viluan
Jay Ar Viluan

Reputation: 59

Yes just replace

return filteredItems; to  return { items: filteredItems }

But please can you check my code if it's correct. Thanks

Upvotes: 0

Related Questions