https://github.com/pixtron/ngxstate
A wrapper library to make using XState state machines in Angular easier
https://github.com/pixtron/ngxstate
Last synced: about 1 year ago
JSON representation
A wrapper library to make using XState state machines in Angular easier
- Host: GitHub
- URL: https://github.com/pixtron/ngxstate
- Owner: pixtron
- License: mit
- Created: 2023-08-16T14:18:43.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-09-05T09:16:43.000Z (almost 3 years ago)
- Last Synced: 2025-03-02T20:48:20.190Z (over 1 year ago)
- Language: TypeScript
- Size: 345 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @pxtrn/ngxstate
This library contains utilities for using [XState](https://github.com/statelyai/xstate) with [Angular](https://github.com/angular/angular#readme).
## Usage
### Use an actor
```ts
import { Component, Injectable } from '@angular/core';
import { createMachine, assign } from 'xstate';
import { AbstractActor, useActor } from '@pxtrn/ngxstate';
const counterMachine = createMachine({
context: {
count: 0,
}
on: {
INC: {
actions: [assign({count: (context) => context.count + 1})]
}
}
});
@Injectable({
providedIn: 'root',
})
export class CounterActor extends AbstractActor {
public readonly actor = useActor(counterMachine);
}
@Component({
template: `
{{ count$ | async }}
+
`
})
export class MyComponent {
private counterActor = inject(CounterActor);
public count$ = this.counterActor.select(state => state.context.count);
public increment() {
this.counterActor.send({type: 'INC'});
}
}
```
### Provide machine implementation
```ts
import { Injectable } from '@angular/core';
import { createMachine, assign } from 'xstate';
import { AbstractActor, AbstractImplementation, useActor } from '@pxtrn/ngxstate';
const counterMachine = createMachine({
context: {
count: 0,
}
on: {
INC: {
actions: ['increment']
}
}
});
type CounterMachine = typeof counterMachine;
@Injectable({
providedIn: 'root',
})
export class CounterImplementation extends AbstractImplementation {
public getImplementation(): MachineImplementation {
return {
actions: {
increment: assign({ count: context => context.count + 42 }),
},
};
}
}
@Injectable({
providedIn: 'root',
})
export class CounterActor extends AbstractActor {
public readonly actor = useActor(counterMachine, {
implementation: inject(CounterImplementation)
});
}
```
### Rehydrate state
```ts
@Injectable({
providedIn: 'root',
})
export class CounterActor extends AbstractActor {
public readonly actor = useActor(counterMachine, {
state: JSON.parse(localStorage.getItem('counterSnapshot')) || undefined
});
public persistState() {
const snapshot = this.actor.getSnapshot();
localStorage.setItem('counterSnapshot', JSON.stringify(snapshot));
}
}
```