Skip to content

Commit

Permalink
chore(docz): remove callbags for state subcribe
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed Jan 22, 2019
1 parent 9f99c30 commit 4162a1c
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions core/docz/src/utils/createState.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,42 @@
import * as React from 'react'
import { createContext, Component } from 'react'
import equal from 'fast-deep-equal'
import observe from 'callbag-observe'
import makeSubject from 'callbag-subject'

export interface ProviderProps<T> {
initial?: T
}

export type PrevState<T> = (prevState: T) => T
export type GetFn<T> = (state: T) => React.ReactNode
export type Dispatch<T> = T | PrevState<T>

export interface State<T> {
get: (fn: GetFn<T>) => React.ReactNode
set: (param: T | PrevState<T>) => void
set: (param: Dispatch<T>) => void
Provider: React.ComponentType<ProviderProps<T>>
}

const subject = makeSubject()
export function create<T = any>(initial: T = {} as T): State<T> {
const { Provider, Consumer }: any = createContext<T>(initial)
const listeners = new Set()

Consumer.displayName = 'StateConsumer'

const dispatch = (fn: Dispatch<T>) => {
listeners.forEach(listener => listener(fn))
}

return {
get: fn => <Consumer>{fn}</Consumer>,
set: fn => subject(1, fn),
set: fn => dispatch(fn),
Provider: class CustomProvider extends Component<ProviderProps<T>, T> {
public static displayName = 'StateProvider'
public state: T = this.props.initial || initial
public componentDidMount(): void {
observe((fn: T) => this.setState(fn))(subject)
listeners.add((fn: Dispatch<T>) => this.setState(fn))
}
public componentWillUnmount(): void {
subject(2)
listeners.clear()
}
public shouldComponentUpdate(nextProps: any, nextState: any): boolean {
return !equal(this.state, nextState)
Expand Down

0 comments on commit 4162a1c

Please sign in to comment.