Nice! Note that you can simplify the updateBook case, by directly finding and mutating an existing book object. I'd write it as:
updateBook
updateBook(state, action: PayloadAction<BookState>) { const {title, id, author} = action.payload; const book = state.booklist.find(book => book.id === id); if (book) { book.author = author; book.title = title; // Alternately: Object.assign(book, {title, author}) } }
Note that you could also simplify this further using RTK's createEntityAdapter API:
createEntityAdapter
const booksAdapter = createEntityAdapter<BookState>(); const initialState = booksAdapter.getInitialState(); const bookSlice = createSlice({ name: 'book', initialState, reducers: { addNewBook: booksAdapter.addOne, updateBook(state, action: PayloadAction<BookState>) { const {id, title, author} = action.payload; booksAdapter.updateOne({id, changes: {title, author}); }, deleteBook: booksAdapter.removeOne } })
and the adapter reducer functions will handle the add/update/remove logic for you.
That's a great addition, thank you!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice! Note that you can simplify the
updateBook
case, by directly finding and mutating an existing book object. I'd write it as:Note that you could also simplify this further using RTK's
createEntityAdapter
API:and the adapter reducer functions will handle the add/update/remove logic for you.
That's a great addition, thank you!