Created
November 7, 2019 08:33
-
-
Save zhanbei/ab083ad04a9ab79d6f8c64f78d0efec2 to your computer and use it in GitHub Desktop.
Simplified states react hook manager for the animations around the process of data fetching/loading.
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
'use strict'; | |
import React from 'react'; | |
// A state hook that supports 5 fetcher states: | |
// | |
// @see [Data Fetching/Loading Animations · Issue #2 · zhanbei/uzbei.com](https://github.com/zhanbei/uzbei.com/issues/2) | |
// ref [streamich/react-use: React Hooks - Github](https://github.com/streamich/react-use) | |
// ref [rehooks/awesome-react-hooks: Awesome React Hooks - Github](https://github.com/rehooks/awesome-react-hooks) | |
// | |
// 1. Loading | |
// 2. Refreshing | |
// 3. Error | |
// 4. Empty Data | |
// 5. Real Data | |
export interface IFetcher { | |
loading: boolean; | |
initializing: boolean; | |
data?: any; | |
error?: any; | |
message: string; | |
} | |
const init: IFetcher = { | |
loading: false, | |
initializing: true, | |
data: undefined, | |
error: undefined, | |
message: 'Loading resources...', | |
}; | |
// Load immediately with following refreshes. | |
export const useNewFetcher = (): [IFetcher, (data?: any, error?: any) => any, () => any] => { | |
const [fetcher, setStatus] = React.useState(init); | |
const fetched = (data: any, error: any) => setStatus({loading: false, initializing: false, data, error, message: error ? 'Error Encountered!' : (data ? '' : 'Empty Data Fetched!')}); | |
const refreshing = () => setStatus({loading: true, initializing: false, data: undefined, error: undefined, message: fetcher.initializing ? 'Loading Data...' : 'Refreshing resources...'}); | |
// const error = (error: any) => setStatus({...fetcher, loading: false, data: undefined, error}); | |
return [fetcher, fetched, refreshing]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment