score:2

Accepted answer

i'm seeing a couple of things here that you should take a look at, and hopefully they'll help you to solve your issue.

first of all, note that your deletepost function expects a parameter with the post id. however, in the jsx code you posted for your button, you're not passing any value to the function at all. this means that the property payload will have an undefined value by the time the action is dispatched.

make sure you update your view to pass it an id, so you call the proper endpoint (your delete request is probably pointing to https://jsonplaceholder.typicode.com/posts/undefined right now) and the reducer actually receives the id of the post you want to remove:

<button key={post.id} onclick={()=>this.props.deletepost(post.id)}>x</button>

the second thing you have to check is the implementation of your reducer. from what i've understood in your message and the code for the deletepost method, action.payload should contain a number.

that being the case, how your reducer is handling the delete_post action in the reducer doesn't make too much sense to me.

case delete_post:
    return {
        ...state,
        items: action.payload
    };

reducers are supposed to be pure functions that, for a given state and action, returns an entirely new state based on the action it receives. remember too that the state you receive cannot be altered at all: if the original instance is mutated in any way, your code will not work.

in this case, you need to return a new state where your items property is replaced by a new list where the id you want to remove is missing. in the piece of code you wrote, however, you're replacing the items array by a number. this is not what was supposed to happen, starting by the fact that items should still be an array of numbers.

what you actually need to do is to create a new array that does not include the item you wanted to remove. you may use the filter method to achieve this:

case delete_post:
    return {
        ...state,
        items: state.items.filter(item => item !== action.payload)
    };

this code should do exactly what you want: here we are assigning the items property in your state an entirely new array where the deleted post is not included.

filter returns an array with the items for which the specified function returns true. in this case, the arrow function we're passing to filter returns true for every item that's different from the id of the post you want to remove.

by using this method you will also have no problems with the initial state.items value being mutated somehow, as filter returns a new instance of array and does not alter the original.


Related Query

More Query from same tag