Last active
November 15, 2019 17:48
-
-
Save baetheus/a68cef83d01b9827b1e0bc3518e1f1b1 to your computer and use it in GitHub Desktop.
Preact hook for @nll/dux AsyncData in an fp-ts Task
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 { 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