I started to learn redux and I have a problem with the code. I would like to delete the note, but when the function executes, I get such an error
" Uncaught TypeError: Cannot read properties of undefined (reading 'filter') at rootReducer"
Can someone solve it?
Action
export const deleteNote = (id) => {
return {
type: 'DELETE_NOTE',
payload: {
id,
},
}
}
Reducers
const initialState = {
notes: [
{
id: 1,
title: 'aaaaaaaaaaaaaaaaaaa',
content: 'xxxxxxxxxxxxxxxxxxxxxxxx',
},
{
id: 2,
title: 'aaaaaaaaaaaaaaaaaaaa',
content: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
},
{
id: 3,
title: 'aaaaaaaaaaaaaaaaaaaa',
content: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
NoteType: 'note',
},
],
}
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'DELETE_NOTE':
return {
...state,
[action.payload.id]: state.notes.filter((item) => item.id !== action.payload.id),
}
default:
return state
}
}
export default rootReducer
Component
const StyledDiv_3 = styled.div`
width: 300px;
height: 400px;
border: 4px solid rgb(80, 208, 228);
display: flex;
flex-direction: column;
align-items: center;
margin: 10px;
position: relative;
`
class Note extends Component {
state = {
redirect: false,
}
render() {
const { title, content, id, deleteNote } = this.props
const { redirect } = this.state
return (
<StyledDiv_3>
<DeleteNote onClick={() => deleteNote(id)}>delete</DeleteNote>
<NoteTitle>{id}</NoteTitle>
<NoteContentContainer>
<NoteContent>{content}</NoteContent>
</NoteContentContainer>
</StyledDiv_3>
)
}
}
Note.protoTypes = {
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
id: PropTypes.number.isRequired,
postType: PropTypes.string.isRequired,
}
Note.defaultProps = {
postType: 'posts',
}
const mapDispatchToProps = (dispatch) => ({
deleteNote: (id) => dispatch(deleteNoteAction(id)),
})
export default connect(null, mapDispatchToProps)(Note)
your return statement in the reducer should look like this:
return {
...state,
notes: state.notes.filter((item) => item.id !== action.payload.id)
}