Immer wrappers around NgRx methods to mutate state easily
npm install ngrx-immer
Do not forget to install immer
Creates an NgRx reducer, but allows you to mutate state without having to use to spread operator.
- Use it when you want to go Immer all the way
- Caveat, you have to return the state with each
on
method
import { createImmerReducer } from 'ngrx-immer/store';
const todoReducer = createImmerReducer(
{ todos: [] },
on(newTodo, (state, action) => {
state.todos.push({ text: action.todo, completed: false });
return state;
}),
on(completeTodo, (state, action) => {
state.todos[action.index].completed = true;
return state;
}),
);
Creates an NgRx reducer, but allows you to mutate state without having to use to spread operator.
- Use it when you want to go sprinkle a little bit of Immer for more complex cases
import { immerOn } from 'ngrx-immer/store';
const todoReducer = createReducer(
{ todos: [] },
on(newTodo, (state, action) => {
return {
...state,
todos: [...state.todos, action.todo],
};
}),
immerOn(completeTodo, (state, action) => {
state.todos[action.index].completed = true;
}),
);
Wraps Immer around the Component Store updater
and setState
methods.
import { ImmerComponentStore } from 'ngrx-immer/component-store';
@Injectable()
export class MoviesStore extends ImmerComponentStore<MoviesState> {
constructor() {
super({ movies: [] });
}
readonly addMovie = this.updater((state, movie: Movie) => {
state.movies.push(movie);
});
}
Inspired by Alex Okrushko, immerReducer
is a reducer method that uses the Immer produce
method.
This method is used by all the methods in ngrx-immer
provides.
- See the Immer docs, Update patterns, on how to mutate state