Skip to content

Instantly share code, notes, and snippets.

@troygoode
Created December 30, 2018 20:27
Show Gist options
  • Save troygoode/7dbee5557c264048ffbbaea96511001a to your computer and use it in GitHub Desktop.
Save troygoode/7dbee5557c264048ffbbaea96511001a to your computer and use it in GitHub Desktop.
Hooks are awesome.
import React, { useMemo } from 'react'
import { usePromise } from 'react-hook-utils'
import useMessages from './use-messages'
import Loading fom './loading'
import Oops fom './oops'
const fetchMessages = async () => {
return fetch('/api/messages')
}
const MessagesAside = () => {
// bind to a global reducer for shared state
const [messages, { set: setMessages }] = useMessages((state) => state.messages)
// initiate remote fetch; pass to shared state
const [, error, loading] = usePromise(
useMemo(() => fetchMessages().then(setMessages), [])
)
if (error) return <Oops />
else if (loading) return <Loading />
else return (
<ul>
{messages.map((msg) => (
<li key={message.id}>{message.text}</li>
))}
</ul>
)
}
export default MessagesAside
import { globalReducer } from 'react-hook-utils'
export default globalReducer(
{ messages: [] },
{
set: (state, messages) => ({
...state,
messages
})
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment