- Fetches data from an async function
- Allows you to manipulate the data à la Redux
- Will throw out outdated API calls by default
Basic usage:
;;; ;
Expand for more advanced usage:
;;; ;
Expand for setting up hook with Context:
;;; ; ;
API
The useData
hook is the only non-type export. The type definition is as
follows:
declare ;
If you are using this in a TypeScript project, you do not need to provide a type
for the generic D
, as it will be automatically parsed from the return type of
asyncFetch
. However in some cases it may be desirable to define it (see more
information in the initialData
section).
It accepts three arguments:
asyncFetch
- () => Promise<D>
Any async fetch function that you want to use to fetch data from. The type will be automatically parsed from the return type.
Example usage:
// If your function takes no arguments, you can pass it in directly:; // If it requires arguments, wrap it in an arrow function:;
initialData
- D
Initial data must match the return type of asyncFetch
, or the generic D
. For
example, the following will result in an error:
;
This is because it expects initialData
to be of type { a: { b: string; }; }
.
To fix this, you will need to define the generic:
;
This will allow the property a
to be either null or { b: string; }
.
options
- UseDataOptions
Options is an optional object that has the following structure:
fireOnMount
- Default: true. Should the hook fire theasyncFetch
on mount.takeEvery
- Default: false. Should the hook take every call rather than throwing out active calls when new ones are made.
@returns
- StatusObject<D>
The hook returns an object with 5 properties:
loading
- True if currently fetching.error
- The error object if your fetch fails, or null if not failed.data
- The data from your async fetch, or null if not fetched.fireFetch
- Fire the async function that was provided to useData. You may pass it an async function to call instead ofasyncFetch
,setData
- Mutate the data. Either a function that takes old data and returns the new data, or data of typeD
. Calling this will turnerror
to null. Additionally takes a parameter to stop loading when called (loading will continue by default).