Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useBlocBuilder hook #40

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions packages/react-bloc/lib/src/hooks/use-bloc-builder.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react'
import { Subscription } from 'rxjs'

interface BlocBuilderOptions {
condition: (previous: any, current: any) => boolean
}

export default function useBlocBuilder(bloc: any, options?: BlocBuilderOptions) {
const [state, setState] = React.useState(bloc.state)
const mounted = React.useRef<any>(false)
const previousState = React.useRef<any>(null)
const subscription = React.useRef<any>(Subscription.EMPTY)
const thisBloc = React.useRef<any>(bloc)

const subscribe = () => {
subscription.current = thisBloc.current.listen((s: any) => {
let rebuild: boolean =
options && options.condition ? options.condition.call(null, state, s) : true

if (rebuild) setState(s)
previousState.current = state
})
}

const unsubscribe = () => {
subscription.current.unsubscribe()
}

React.useLayoutEffect(() => {
if (!mounted.current) {
mounted.current = true
subscribe()
} else {
unsubscribe()
thisBloc.current = bloc
subscribe()
}
return () => unsubscribe()
})

return { state }
}