Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Created April 24, 2019 12:27
Show Gist options
  • Save beardedtim/7fdc024b63b35eb55a03ee74ab660d20 to your computer and use it in GitHub Desktop.
Save beardedtim/7fdc024b63b35eb55a03ee74ab660d20 to your computer and use it in GitHub Desktop.
Example of creating a hook instead of an HoC-type thing
import React, { useEffect, useState } from 'react'
import { render } from 'react-dom'
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'
const getPusher = () => interval(500).pipe(
map(() => ({ message: 'New Pusher Message', time: new Date() }))
)
const usePusher = () => {
const [isSubscribed, setSubscribed] = useState(false)
const [stepOutput, setStepOutput] = useState([])
useEffect(() => {
const pusherUpdate$ = getPusher()
const subscription = pusherUpdate$.subscribe(
message => setStepOutput(oldSteps => ([...oldSteps, message]))
)
setSubscribed(true)
return () => subscription.unsubscribe()
}, [stepOutput])
return { stepOutput, isSubscribed }
}
const App = () => {
const { stepOutput, isSubscribed } = usePusher()
if (!isSubscribed) {
return 'Loading...'
}
return (
<div>
{stepOutput.map((_, i) => <p key={i}>Number {i + 1} of step output</p>)}
</div>
)
}
render(
<App />,
document.getElementById('app')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment