React hook for loading data
Using npm:
$ npm install --save react-use-data-loader
Using yarn:
$ yarn add react-use-data-loader
Since this module uses React's upcoming Hooks feature, to try this out you'll need to install the 16.7.0-alpha.0 version of react and react-dom:
$ yarn add [email protected] [email protected]
import React from 'react'
import { useDataLoader } from 'react-use-data-loader'
async function getData(id) {
/* async api call */
return 'item ' + id
}
function Example({ id }) {
const { data, error, loading, retry } = useDataLoader(getData, id)
if (loading) {
return <div>loading...</div>
}
if (error) {
return <div>Error</div>
}
return <ViewData data={data} />
}
function App() {
return <Example id={3} />
}
useDataLoader(getData: GetData, ...args: Args) => ({
data: Data | null,
error: Error | null,
loading: boolean,
retry: Retry,
})
type GetData = (...args: Args) => Promise<Data>
type Retry = () => void