cached-effect v1.0.1-beta0
Cached effects in React + hooks
Manage effects in React using async functions and hooks
Installation
npm install cached-effector
yarn add cached-effectUsage
import { createEffect, useCache } from './cached-effect'createEffect function
Wrap an async function (that returns promise) in createEffect:
export const fetchUsers = createEffect(({ organizationId }) => http
.get(`/organizations/${organizationId}/users`)
.then(getData)
.then(getUsers))useCache hook
Then wrap your effect in useCache hook in your React component:
const [users, usersError] = useCache(fetchUsers)useCache returns an array of [result, error] which is
equal to [undefined, null] by default.
Running effects
In order to populate the cache you need to run your effect in your component:
useEffect(() => {
fetchUsers({ organizationId }) // or fetchUsers.once (see below)
}, [])In the above example, users will be fetched after the component is mounted.
You can also refetch users (trigger any effect) manually just calling it:
<Button
type='button'
onClick={() => fetchUsers({ organizationId })}
/>.once() method
You can run your effect only once, for example, if you have many components using this effect:
useEffect(() => {
fetchUsers.once({ organizationId })
}, [])usePending hook
If you need to show a spinner for example, you can use usePending hook
to get current pending status (true/false):
const usersLoading = usePending(fetchUsers)useError hook
If you need to show only an error somewhere for this effect, use useError hook
to get current error (or null if your effect is done successfully):
const usersError = useError(fetchUsers)Tip
If you found this hook useful, please star this package on GitHub ★
Author
@doasync
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
