Skip to main content

Immer

Immer plugin for Rematch. Wraps your reducers with immer, providing ability to safely do mutable changes resulting in immutable state.

Compatibility

Install the correct version of immer plugin based on the version of the core Rematch library in your project.

@rematch/core@rematch/immer
1.x.x1.x.x
2.x.x2.x.x

Install

bash
npm install immer @rematch/immer
bash
npm install immer @rematch/immer

immerPlugin([config])

Immer plugin accepts one optional argument - config, which is an object with the following properties:

  • [whitelist] (string[]): an array of models' names. Allows defining on a model level, which reducers should be wrapped with immer.
  • [blacklist] (string[]): an array of models' names. Allows defining on a model level, which reducers should not be wrapped with immer.

If config isn't provided, reducers from all models will be wrapped with immer.

Usage

In Immer, reducers can perform mutations to achieve the next immutable state. Immer doesn't require that you return the next state from a reducer and Rematch won't force you to do it.

store.ts
ts
// @filename: store.ts
import immerPlugin from "@rematch/immer"
import { init, RematchDispatch, RematchRootState } from "@rematch/core"
import { models, RootModel } from "./models"
 
export const store = init<RootModel>({
models,
// add immerPlugin to your store
plugins: [immerPlugin()],
})
 
export type Store = typeof store
export type Dispatch = RematchDispatch<RootModel>
export type RootState = RematchRootState<RootModel>
store.ts
ts
// @filename: store.ts
import immerPlugin from "@rematch/immer"
import { init, RematchDispatch, RematchRootState } from "@rematch/core"
import { models, RootModel } from "./models"
 
export const store = init<RootModel>({
models,
// add immerPlugin to your store
plugins: [immerPlugin()],
})
 
export type Store = typeof store
export type Dispatch = RematchDispatch<RootModel>
export type RootState = RematchRootState<RootModel>
todo.ts
ts
// @filename: todo.ts
import { createModel } from "@rematch/core"
import { RootModel } from "./models"
 
export const todo = createModel<RootModel>()({
state: [
{
todo: "Learn typescript",
done: true,
},
{
todo: "Try immer",
done: false,
},
],
reducers: {
done(state) {
// mutable changes to the state
state.push({ todo: "Tweet about it", done: false })
state[1].done = true
},
},
})
todo.ts
ts
// @filename: todo.ts
import { createModel } from "@rematch/core"
import { RootModel } from "./models"
 
export const todo = createModel<RootModel>()({
state: [
{
todo: "Learn typescript",
done: true,
},
{
todo: "Try immer",
done: false,
},
],
reducers: {
done(state) {
// mutable changes to the state
state.push({ todo: "Tweet about it", done: false })
state[1].done = true
},
},
})