How Can I Remove An Object From An Array State In Redux/react
I want to remove an object from an array onClick when I click on the delete button, I write some code in my redux and react as well and it is not working !! My reducers import { Ac
Solution 1:
Try this code :
in yours reducers :
exportconstremoveEventReducer = (state = initialState,action) => {
switch(action.type) {
caseActionsTypes.REMOVE_EVENT :
return {... state, events : state.events.filter((event) => event.id !== action.payload)} // payload = id in this casedefault :
return state;
}
then in your Event Component who contains the button :
importReactfrom'react'import { useSelector, useDispatch } from'react-redux';
import { RemoveEvent} from'../Redux/Actions/ActionsEvents';
constEvent = () => {
const events = useSelector((state)=> state.allEvents.events);
const removeEvents = useSelector((state)=> state.removeEvents);
const dispatch = useDispatch();
constremoveEventHandler = (id) => {
dispatch(RemoveEvent(id))
}
return (
<section>
{events.map((singleEvent)=> {
const {title, id, day} = singleEvent;
return (
<articleclassName="event-pop-up"key={id} ><h1>The Name of your Event is <span>{title}</span></h1><buttonclassName="btn event"onClick={()=> removeEventHandler(id)}>
Delete Event</button></article>
)
})}
</section>
)
}
exportdefaultEvent;
then in your RemoveEvent action
export const RemoveEvent = (id) => {
return {
type : ActionsTypes.REMOVE_EVENT, payload: id
};
};
Solution 2:
You can remove an event using it's id.
constremoveEventHandler = (id) => {
dispatch(RemoveEvent(id))
}
return (
<section>
{events.map((singleEvent)=> {
const {title, id, day} = singleEvent;
return (
<articleclassName="event-pop-up"key={id} ><h1>The Name of your Event is <span>{title}</span></h1><buttonclassName="btn event"onClick={() => removeEventHandler(id)}>
Delete Event</button></article>
)
})}
</section>
After passing this id
to the reducer you can loop through the events array and remove this event from array and set the new state.
And in your reducers, you can use filter()
method to remove a particular event having that id
exportconstremoveEventReducer = (state = initialState, action) => {
switch(action.type) {
caseActionsTypes.REMOVE_EVENT :
return {... state, events : state.events.filter((event) => event.id !== action.payload)}
default :
return state;
}
}
For Remove Event Action:
export const RemoveEvent = (id) => {
return {
type : ActionsTypes.REMOVE_EVENT,
payload: id,
};
};
Post a Comment for "How Can I Remove An Object From An Array State In Redux/react"