-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStore.ts
More file actions
30 lines (24 loc) · 733 Bytes
/
Store.ts
File metadata and controls
30 lines (24 loc) · 733 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
type Subscription = <S>(state: S) => void
type SetState<State> = ((prevState: State) => State) | State
export default class Store<State> {
state?: State
subscriptions: Subscription[] = []
constructor(initialState: State) {
this.state = initialState
}
setState<U extends SetState<State>>(updater: U) {
this.state = typeof updater === 'function' ? updater(this.state) : updater
this.subscriptions.forEach(subscription => subscription(this.state))
}
getState() {
return this.state
}
subscribe(subscription: Subscription) {
this.subscriptions.push(subscription)
return () => {
this.subscriptions = this.subscriptions.filter(
item => item !== subscription
)
}
}
}