Last active
March 10, 2021 00:06
-
-
Save joeldenning/f09589dc4662f6d368d0a7b7b938c201 to your computer and use it in GitHub Desktop.
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 { useEffect, useState } from 'react'; | |
function ShowUsers() { | |
const [searchValue, setSearchValue] = useState("") | |
const [fetchUser, user] = useActionState(fetchUserAction) | |
return ( | |
<> | |
<input type="text" value={searchValue} onChange={evt => setSearchValue(evt.target.value)}></input> | |
<button onClick={() => fetchUser(searchValue)}></button> | |
<div>{user && user.emailAddress}</div> | |
</> | |
) | |
} | |
function fetchUserAction(user, setUser, currentSearch) { | |
const abortController = new AbortController() | |
fetch(`/api/user/${currentSearch}`, { signal: abortController.signal }).then(r => r.json()).then(setUser) | |
return () => abortController.abort(); | |
} | |
function useActionState(action, initialValue) { | |
const [state, setState] = useState(initialValue) | |
const [shouldRunAction, setShouldRunAction] = useState(false) | |
const [extraArgs, setExtraArgs] = useState([]) | |
useEffect(() => { | |
if (shouldRunAction) { | |
return action(state, setState, ...extraArgs) | |
} | |
}, [shouldRunAction, state]) | |
useEffect(() => { | |
if (shouldRunAction) { | |
setShouldRunAction(false) | |
} | |
}, [shouldRunAction]) | |
function performAction(...extraArgs) { | |
setExtraArgs(...extraArgs) | |
setShouldRunAction(true) | |
} | |
return [performAction, state, setState] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment