BARNOWL
BARNOWL

Reputation: 3589

Redux dispatch is not removing an item from the array

I'm trying to remove an item from an array, the redux logger shows that everything went well.

enter image description here

However it still shows under the ordered list, after i click the x.

enter image description here

Reducer/posts.js

    case 'REMOVE_POST': {
      return Object.assign({}, state, {
        posts: [...state.posts.filter(post=> post.id !== action.id)],
      });

      }

      default:
        return state
  }

components/TodoList.js

import React from 'react';
import {connect} from 'react-redux';
import { deletePost } from '../actions'

const PostList = ({posts, deletePost}) => (
  <ul className="list-group">
    {posts.map(post=>
      <li
       className="list-group-item" key={post.id} {...post}>  {post.text}
       <button type="submit" onClick={()=> deletePost(post.id)} className =" btn btn-small-primary"> X </button>
      </li>

    )}

  </ul>


);

const mapStateToProps = (state) => {
  return { posts: state.posts };
};

const mapDispatchToProps = dispatch => ({
  deletePost: id => dispatch(deletePost(id))
})


export default connect(mapStateToProps, mapDispatchToProps)(PostList);

Updated.

enter image description here

**ADD_POST reducer**

case 'ADD_POST':
  return [
    ...state,
    {
      id:action.id,
      text:action.text,
    }

  ]

Upvotes: 0

Views: 818

Answers (2)

BARNOWL
BARNOWL

Reputation: 3589

This worked for me, thanks you folks for your contributions.

  switch(action.type){
    case 'ADD_POST':
      return [
        ...state,
        {
          id:action.id,
          text:action.text,
        }

      ]

    case 'DELETE_POST':
      return state.filter(({ id }) => id !== action.id);

    default:
      return state
  }

}

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281606

Well you have a small mistake in your code

The action that you have dispatched is DELETE_POST whereas you expect REMOVE_POST in your code

case 'DELETE_POST': {
      return Object.assign({}, state, {
        posts: [...state.posts.filter(post=> post.id !== action.id)],
      });

      }

      default:
        return state

Upvotes: 1

Related Questions