Reputation: 403
I have a state array that I want to delete an object from. For example, I have:
[
{
name:'bench',
weight: 200
},
{
name:'squat',
weight: 300
},
]
I want to give the user the option to delete an exercise if they wanted to, but I can't figure out how. Here is my reducer:
const initialState = [];
const movementReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_MOVEMENT:
return [
...state, action.payload
];
case UPDATE_MOVEMENT:
return [
...state.map(item => item.movementName === action.payload.movementName ? action.payload : item )
];
case DELETE_MOVEMENT:
return [
state.filter(item => item.movementName === action.payload.movementName ? "true" : "false" )
];
default:
return state;
}
};
export default movementReducer;
With the code I have now, I get nothing returned on the page, but I can still see my state in my redux devtools, meaning it's still there. Any help?
Upvotes: 1
Views: 106
Reputation: 2473
In you're filter you're returning "true"
or "false"
from your comparison, but both those values are truthy: e.g. Boolean("false") === true
.
Change your movement reducer to look like:
const movementReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_MOVEMENT:
return [
...state, action.payload
];
case UPDATE_MOVEMENT:
return [
...state.map(item => item.movementName === action.payload.movementName ? action.payload : item )
];
case DELETE_MOVEMENT:
return [
...state.filter(item => item.movementName === action.payload.movementName)
];
default:
return state;
}
};
I simplified the filter function as having a ternary was redundant.
As a note, this function is comparing the movementName
prop as that's what the original code had, but the code example you provided for those items used name
as the prop. I am not sure which one is correct but be sure they match 😀
Upvotes: 1