Skip to content

Instantly share code, notes, and snippets.

@r17x
Created April 17, 2024 18:18
Show Gist options
  • Save r17x/ffe24442bd97ff8627874a87ba007d46 to your computer and use it in GitHub Desktop.
Save r17x/ffe24442bd97ff8627874a87ba007d46 to your computer and use it in GitHub Desktop.
react_only
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