Zero boilerplate application state with @zodiac-ui/store for Angular

Michael Muscat
Jul 16 · 4 min read
Set state directly using @zodiac-ui/store

Walkthrough

Installation

npm install @zodiac-ui/store immer

Configuration

export interface AppState {
count: number
}
export const initialState: AppState = {
count: 0,
}
@NgModule({
imports: [
StoreModule.forRoot(initialState)
]
})
export class AppModule {}

Getting/Setting State

@Component({
selector: “app-root”,
template: `
<button (click)=”increment()”>Increment</button>
<pre>{{ store | async | json }}</pre>
`,
})
export class AppComponent {
constructor(public store: Store<AppState>) {
store.subscribe(state => console.log(state))
}
public increment(): void {
this.store.next(state => (state.count += 1))
}
}
const selectCount = select(state => state.count)store.pipe(selectCount).subscribe(count => console.log(count))

Writing Effects

export class AppEffects {
constructor(public store: Store, public effects: Effects) {}
}
export function countdown(ctx: AppEffects) {
return ctx.store.pipe(
selectCount,
filter(count => count > 0),
delay(1000),
// Convenient wrapper for store.next()
setState(ctx.store, (state, count) => {
state.count = count — 1
}),
)
}
@NgModule({
imports: [
EffectsModule.forRoot([countdown], {
context: AppEffects,
}),
],
providers: [AppEffects],
})
export class AppModule {}
export function spyOnCountdown(ctx: AppEffects) {
return ctx.effects.pipe(
ofEffect(countdown),
tap(count => console.log(`Last count: ${count}`)),
)
}

Dispatching Actions

export type SomeAction = Action<{
type: “SOME_ACTION”
payload: string
}>
export const someAction = action<SomeAction>(“SOME_ACTION”)
constructor(actions: ActionDispatcher, http: HttpClient) {
actions.next(someAction(“https://repl.to"))
}
actions.pipe(
ofAction(someAction)
switchMap(action => http.get(action.payload))
).subscribe(res => console.log(res))

Global Store

export class AppModule {
constructor(store: GlobalStore) {
store.subscribe(state => console.log(state))
store.next({
root: {
count: 1,
},
})
}
}

Next up


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade