Last active
October 10, 2023 20:49
-
-
Save cowboyd/656b7bf83cb5a4065d571bc5523cda40 to your computer and use it in GitHub Desktop.
useResource hook to use Effection v3 resource.
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 { run, type Operation } from "effection"; | |
import { useEffect, useState, type DependencyList } from "react"; | |
export type ResourceHandle<T> = { | |
type: 'pending'; | |
} | { | |
type: 'resolved'; | |
value: T; | |
} | { | |
type: 'rejected'; | |
error: Error; | |
} | |
export function useResource<T>(resource: Operation<T>, deps: DependencyList = []): ResourceHandle<T> { | |
let [state, setState] = useState<ResourceHandle<T>>({ type: 'pending' }); | |
useEffect(() => { | |
let task = run(function*() { | |
try { | |
yield* call(function*() { | |
let value = yield* resource; | |
setState({ type: 'resolved', value }); | |
yield* suspend(); | |
}); | |
} catch (error) { | |
setState({ type: 'rejected', error }); | |
} | |
}); | |
return () => task.halt(); | |
}, deps as unknown[]); | |
return state; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment