Created
April 24, 2019 12:27
-
-
Save beardedtim/7fdc024b63b35eb55a03ee74ab660d20 to your computer and use it in GitHub Desktop.
Example of creating a hook instead of an HoC-type thing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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