Quick Start

Show me the code

You find a demo using ngrx-ducks at ngrx-ducks-12. More explanations in another format here Api Discussion​

Start with Ducks

Follow this document up along with this demo ngrx-ducks-12. There you will find the entire code that is shown in this article.πŸ’Ž

Implement State Mutations

First create a file where the mutation logic for a certain state slice should live. Put selectors logic here as well.
Add a class that implements the needed Case Reducers, builds required selectors and triggers actions.
createDuck supports to create both triggering actions (for Effects) and mutating actions. Second parameter of createDuck is a Case Reducer. It has a similar style of creating a reducer which actually makes state mutations.
counter.facade.ts
1
import { createDuck } from '@ngrx-ducks/core';
2
​
3
@StoreFacade()
4
export class CounterFacade {
5
counter = bindSelectors({ count: selectors.currentCount });
6
7
loadCount = createDuck('[Counter] Set initial value',
8
(state: CounterState, payload: number) => {
9
return { ...state, count: payload };
10
});
11
}
Copied!
The decorator StoreFacade introduces a new mechanism how the Facade is connected with the Store.πŸš€

Create Reducer automatically

If you use Ducks there is no need to maintain switch-case statements. Now you can create the Reducer based on the Ducks you have created inside the Facade class.
counter.facade.ts
1
import { createDuck, getReducer, StoreFacade } from '@ngrx-ducks/core';
2
​
3
@StoreFacade()
4
export class CounterFacade {
5
duck1 = createDuck('Duck 1', /* reducer function */);
6
duck2 = createDuck('Duck 2', /* reducer function */);
7
duck3 = createDuck('Duck 3', /* reducer function */);
8
}
9
​
10
// declare initial state and export counterReducer
11
const initialState = { count: 0 };
12
export const counterReducer = getReducer(initialState, CounterFacade);
Copied!
Just created counterReducer is a variable which can be used in ngrx method combineReducers doc. From that point our implementation of a reducer is finished. Example below shows us basic implementation.
index.ts
1
import { Action, combineReducers, MetaReducer } from '@ngrx/store';
2
import { CounterState, counterReducer } from './counter';
3
​
4
export interface State {
5
simple: CounterState;
6
}
7
​
8
export function reducers(state: State, action: Action) {
9
return combineReducers<State>({
10
simple: counterReducer
11
})(state, action);
12
}
13
​
14
export const metaReducers: MetaReducer<State>[] = [];
Copied!

Inject the StoreFacade Service

To use your Facade you need to inject it into your component.
counter.component.ts
1
@Component({/* ... */})
2
export class CounterComponent {
3
constructor(private counter: CounterFacade) {}
4
}
Copied!
Since the whole logic is implemented in a Facade (CounterFacade in our case) we only need to import that Facade.
πŸŽ‰ The API allows you to create dynamic facades and your components do not even know that Redux is working behind the scenes. We only rely on the contracts that we use messaging and streams.
πŸ‘“Thanks to TypeScript each method is strictly typed and the whole process of creating or dispatching Actions is transparent.
counter.component.ts
1
@Component({/* ... */})
2
export class CounterComponent implements OnInit {
3
/* ... */
4
​
5
ngOnInit() {
6
this.counter.loadCount.dispatch(5000);
7
// ^ only type number is allowed πŸŽ‰
8
// - dispatches action: type: '[Counter] Set initial value'
9
// payload: 5000
10
}
11
}
Copied!

Use NgRx's selectors

Creating selectors is the same way as it's in NgRx.
counter.facade.ts
counter.selectors.ts
counter.selectors.ts
1
import { bindSelectors, StoreFacade } from '@ngrx-ducks/core';
2
​
3
import * as selectors from './counter.selectors';
4
​
5
@StoreFacade()
6
export class CounterFacade {
7
select = bindSelectors(selectors);
8
}
Copied!
1
import
2
​
3
// counter.component.ts
4
import { currentCount } from './counter.selectors';
5
​
6
export class CounterComponent {
7
counter$: Observable<number>;
8
​
9
constructor(private counter: CounterFacade) {
10
this.count$ = this.counter.select.currentCount;
11
}
12
}
Copied!
1
import { createFeatureSelector, createSelector } from '@ngrx/store';
2
import { State } from '..';
3
​
4
const visitCounter = createFeatureSelector<State>('counter');
5
​
6
export const currentCount = createSelector(
7
visitCounter,
8
counter => counter.simple.count
9
);
Copied!

What if I don't want to dispatch the action directly?

No worries, ngrx-ducks gets you covered in this question. Each dispatching method provides an Action Creator.
component.ts
1
ngOnInit() {
2
// Yields Action
3
this.counter.loadCount(5000);
4
// {
5
// type: '[Counter] Set initial value',
6
// payload: 5000
7
// }
8
​
9
// Dispatches an action
10
this.counter.loadCount.dispatch(5000);
11
​
12
}
Copied!
You see .loadCount(5000); is a method as well. 🀯 This addition is very useful if you need to produce actions being returned by an Effect.

Effects

You may wonder if @ngrx-ducks can help you with actions being dispatched to an Effect. Short answer: Yes, it can.

Setup

Let's use createDuck again! createDuck is the only entry point you need to know to create and dispatch actions. It works with calling Effects as well. It works with Effects just like actions work with Effects in ngrx.
counter.facade.ts
1
import { createDuck } from '@ngrx-ducks/core';
2
​
3
@StoreFacade()
4
export class CounterFacade {
5
​
6
readonly loadCount = createDuck('[Counter] Load Count', dispatch<number>());
7
​
8
// another action (called in Effect below)
9
override = createDuck('[Counter] Set value',
10
(state: CounterState, payload: number) => {
11
return { ...state, count: payload };
12
}
13
);
14
}
15
​
16
export const counterActions = getActions(CounterFacade);
Copied!

Triggering an Effect

counter.component.ts
1
import { currentCount } from './counter.selectors';
2
​
3
@Component({
4
/* ... */
5
})
6
export class CounterComponent {
7
counter$: Observable<number>;
8
​
9
constructor(private counter: CounterFacade) {
10
// let's dispatch an action which is handled by an Effect
11
this.counter.loadCount.dispatch(10);
12
}
13
}
Copied!

Inside Effects

The last question is how an Effect itself handles actions with ngrx-ducks. An Effect filters the action type first. Let NgRx do it!😁
counter.effects.ts
1
import { Actions, createEffect, ofType } from '@ngrx/effects';
2
import { counterActions } from './counter.facade';
3
​
4
@Injectable()
5
export class CounterEffects {
6
setCounter = createEffect(() => this.actions$.pipe(
7
ofType(counterActions.loadCount),
8
delay(2000),
9
map(({ payload }) => counterActions.override(payload))
10
));
11
​
12
constructor(private actions$: Actions) {}
13
}
Copied!
As mentioned before, you can make use of the generated, typed action creators to create an action that is handled by the Effect.
You see the only API you have to work with is the Ducks-API. It does not change anything in [ngrx] but automates the process dealing with actions.
Last modified 3mo ago