DEV Community

Discussion on: Up & Running with React, Redux Toolkit, Typescript and React Router

Collapse
 
markerikson profile image
Mark Erikson

Nice! Note that you can simplify the updateBook case, by directly finding and mutating an existing book object. I'd write it as:

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})
  }
}

Enter fullscreen mode Exit fullscreen mode

Note that you could also simplify this further using RTK's createEntityAdapter API:

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
  }
})
Enter fullscreen mode Exit fullscreen mode

and the adapter reducer functions will handle the add/update/remove logic for you.


Enter fullscreen mode Exit fullscreen mode
Collapse
 
ogzhanolguncu profile image
Oğuzhan Olguncu

That's a great addition, thank you!