-
-
Save r17x/ffe24442bd97ff8627874a87ba007d46 to your computer and use it in GitHub Desktop.
react_only
This file contains 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
const idle = () => ({ kind: 'idle' }) | |
const loading = () => ({ kind: 'loading' }) | |
const loaded = (data) => ({ kind: 'loaded', data }) | |
const error = (error) => ({ kind: 'error', error }) | |
const isLoaded = (state) => state.kind === 'loaded' | |
const renderWhenLoaded = (state, reactNode) => isLoaded(state) | |
? reactNode(state.data) | |
: null | |
const noOp = () => {} | |
const doItSafely = (ref, effect) => (...args) => ref!==null | |
? effect(...args) | |
: noOp() | |
const Component = () => { | |
const [ state, dispatch_ ] = React.useState(idle) | |
const ref = React.useRef(null) | |
cosnt dispatch = doItSafely(ref, dispatch_) | |
React.useEffect(() => { | |
dispatch(loading) | |
const run = doItSafely( | |
() => fetch(`https://api.github.com/users/r17x`) | |
.then(res => res.json()) | |
.then(loaded) | |
.then(dispatch) | |
.catch(e => dispatch(error(e))) | |
) | |
run() | |
return () => { | |
ref.current = null | |
} | |
}) | |
return ( | |
<> | |
<span ref={ref} style={{display: 'none'}} /> | |
{renderWhenLoaded(state, data => <User {...data} />)} | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment