https://github.com/tlmader/ng-set-state
Strongly typed function that safely mutates this.state for an Angular component
https://github.com/tlmader/ng-set-state
angular typescript
Last synced: 2 months ago
JSON representation
Strongly typed function that safely mutates this.state for an Angular component
- Host: GitHub
- URL: https://github.com/tlmader/ng-set-state
- Owner: tlmader
- Created: 2018-10-05T14:27:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-10-05T14:32:56.000Z (over 7 years ago)
- Last Synced: 2025-06-14T19:35:56.984Z (about 1 year ago)
- Topics: angular, typescript
- Language: TypeScript
- Homepage:
- Size: 1000 Bytes
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ng-set-state
Returns a strongly typed function that safely mutates this.state for the given context.
1. Set up State interface and initial state:
```
const initialState = {
counter: 0
};
type State = Readonly;
```
2. Initialize state and setState inside component
```
export class StepperComponent {
readonly state: State = initialState;
readonly setState = createSetState(this);
}
```
Returned function (setState) accepts an updater function with the signature:
```
(previousState) => nextState
```
State is a reference to the component state at the time the change is being applied. It should not be directly
mutated. Instead, changes should be represented by building a new object based on the input from state. For
instance, suppose we wanted to increment a value in state by 1:
```
handleStep(): void {
this.setState((previousState) => ({
counter: previousState.counter + 1
}));
}
```
State received by the updater function is the previous state. The next state will be the output of the updater.
This paradigm allows us to extract state update functions to pure functions outside the class.
```
const incrementCounter = (previousState: State) => ({ counter: previousState.counter + 1 });
export class StepperComponent {
readonly state: State = initialState;
readonly setState = createSetState(this);
handleStep(): void {
this.setState(incrementCounter);
}
}
```