Skip to content

Instantly share code, notes, and snippets.

@joeldenning
Last active March 10, 2021 00:06
Show Gist options
  • Save joeldenning/f09589dc4662f6d368d0a7b7b938c201 to your computer and use it in GitHub Desktop.
Save joeldenning/f09589dc4662f6d368d0a7b7b938c201 to your computer and use it in GitHub Desktop.
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