dim_dev
dim_dev

Reputation: 359

How to delete specific item from Redux state?

When I click delete I get the Can not read property 'id' of null error. I am confused.* How to pass the id so only the component I clicked on (delete button) is removed?**

Reducer:


const notesReducer = (state = notes, action, id) => {
  switch (action.type) {
    case 'ADD':
      return [...state, action.newItem]

    case 'DELETING':
      //const newState = [...state.filter((note) => note !== action.note)]
      const newState = [...state]
      newState.filter((note) => note.id !== action.payload.id)
    //newNote.pop()

    default:
      return state
  }
}

Action

export const add = (id) => {
  return {
    type: 'ADD',
  }
}

export const deleting = (id) => {
  return {
    type: 'DELETING',
  }
}

Component

   <div>
          {notes.map((item, index) => (
            <div>
              <Select></Select>
              <Dialog key={uuid()}></Dialog>
              <Button
                key={uuid()}
                onClick={deleteNote}
              >
                Delete
              </Button>
            </div>
          ))}
        </div>
dispatch({ type: 'ADD', mynote }),
dispatch({ type: 'DELETING' })

Upvotes: 1

Views: 1504

Answers (1)

Song
Song

Reputation: 750

Based on your current implementation, you need to pass note id to

dispatch({ type: 'DELETING', note.id })

Also, in reducer, you need to return modified state.

    case 'DELETING':
      return state.filter((note) => note.id !== id)

As an advice, you actually don't use actions you defined, because you directly dispatch with type. So, keep in mind that it's a better approach to write actions and fire them using mapDispatchToProps.

Upvotes: 1

Related Questions