Last active
February 21, 2020 16:04
-
-
Save jonaskuske/9c7b6a090fe18a8ad1f24025e60c27aa to your computer and use it in GitHub Desktop.
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 React, { useState, useEffect, useCallback } from 'react' | |
export const IDLE = 'IDLE' | |
export const LOADING = 'LOADING' | |
export const SUCCESS = 'SUCCESS' | |
export const ERROR = 'ERROR' | |
export function useAsyncData(fetchFn, deps) { | |
const stableFetchFn = useCallback(fetchFn, deps) | |
const [{ state, data, error }, setState] = useState({ state: IDLE }) | |
useEffect(() => { | |
let active = true | |
setState(prev => ({ ...prev, state: LOADING })) | |
stableFetchFn().then( | |
data => active && setState({ state: SUCCESS, data }), | |
error => active && setState({ state: ERROR, error }), | |
) | |
return () => (active = false) | |
}, [stableFetchFn]) | |
return { state, data, error } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment