Skip to content

Instantly share code, notes, and snippets.

@jonaskuske
Last active February 21, 2020 16:04
Show Gist options
  • Save jonaskuske/9c7b6a090fe18a8ad1f24025e60c27aa to your computer and use it in GitHub Desktop.
Save jonaskuske/9c7b6a090fe18a8ad1f24025e60c27aa to your computer and use it in GitHub Desktop.
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