Skip to content

Instantly share code, notes, and snippets.

@baetheus
Last active November 15, 2019 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baetheus/a68cef83d01b9827b1e0bc3518e1f1b1 to your computer and use it in GitHub Desktop.
Save baetheus/a68cef83d01b9827b1e0bc3518e1f1b1 to your computer and use it in GitHub Desktop.
Preact hook for @nll/dux AsyncData in an fp-ts Task
import { DatumEither, failure, initial, toRefresh } from '@nll/datum/lib/DatumEither';
import { Task } from 'fp-ts/lib/Task';
import { Errors } from 'io-ts';
import { useEffect, useState } from 'preact/hooks';
export const useTaskDatumEither = <T>(task: Task<DatumEither<Errors, T>>) => {
const [state, setState] = useState<DatumEither<Errors, T>>(initial);
useEffect(() => {
// Setup "cancellation closure"
let linked = true;
// Initialze loading state
setState(toRefresh(state));
task()
.then(d => {
if (linked) {
setState(d);
}
})
.catch(() => setState(failure([])));
return () => (linked = false);
}, [task]);
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment