Skip to content

Commit 6dc9363

Browse files
committed
copy over adapter TS section from RTK docs
1 parent 364c1cc commit 6dc9363

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

docs/usage/UsageWithTypescript.md

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,35 @@ const fetchUserById = createAsyncThunk<
634634

635635
### Typing `createEntityAdapter`
636636

637-
Typing `createEntityAdapter` only requires you to specify the entity type as the single generic argument. This typically looks like:
637+
Usage of `createEntityAdapter` with Typescript varies based on whether your entities are normalized by an `id` property, or whether a custom `selectId` is needed.
638+
639+
If your entities are normalized by an `id` property, `createEntityAdapter` only requires you to specify the entity type as the single generic argument. For example:
640+
641+
```ts
642+
interface Book {
643+
id: number
644+
title: string
645+
}
646+
647+
// no selectId needed here, as the entity has an `id` property we can default to
648+
// highlight-next-line
649+
const booksAdapter = createEntityAdapter<Book>({
650+
sortComparer: (a, b) => a.title.localeCompare(b.title)
651+
})
652+
653+
const booksSlice = createSlice({
654+
name: 'books',
655+
initialState: booksAdapter.getInitialState(),
656+
reducers: {
657+
bookAdded: booksAdapter.addOne,
658+
booksReceived(state, action: PayloadAction<{ books: Book[] }>) {
659+
booksAdapter.setAll(state, action.payload.books)
660+
}
661+
}
662+
})
663+
```
664+
665+
On the other hand, if the entity needs to be normalized by a different property, we instead recommend passing a custom `selectId` function and annotating there. This allows proper inference of the ID's type, instead of having to provide it manually.
638666

639667
```ts
640668
interface Book {
@@ -643,18 +671,15 @@ interface Book {
643671
// ...
644672
}
645673

646-
// highlight-next-line
647674
const booksAdapter = createEntityAdapter({
675+
// highlight-next-line
648676
selectId: (book: Book) => book.bookId,
649677
sortComparer: (a, b) => a.title.localeCompare(b.title)
650678
})
651679

652680
const booksSlice = createSlice({
653681
name: 'books',
654-
// highlight-start
655-
// The type of the state is inferred here
656682
initialState: booksAdapter.getInitialState(),
657-
// highlight-end
658683
reducers: {
659684
bookAdded: booksAdapter.addOne,
660685
booksReceived(state, action: PayloadAction<{ books: Book[] }>) {

0 commit comments

Comments
 (0)