Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active October 10, 2023 20:49
Show Gist options
  • Save cowboyd/656b7bf83cb5a4065d571bc5523cda40 to your computer and use it in GitHub Desktop.
Save cowboyd/656b7bf83cb5a4065d571bc5523cda40 to your computer and use it in GitHub Desktop.
useResource hook to use Effection v3 resource.
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