Created
December 30, 2018 20:27
-
-
Save troygoode/7dbee5557c264048ffbbaea96511001a to your computer and use it in GitHub Desktop.
Hooks are awesome.
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
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 |
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
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