1.0.1-beta0 • Published 7 years ago

cached-effect v1.0.1-beta0

Weekly downloads
36
License
MIT
Repository
github
Last release
7 years ago

Cached effects in React + hooks

NPM Version NPM Downloads GitHub issues Telegram

Manage effects in React using async functions and hooks

Installation

npm install cached-effect

or

yarn add cached-effect

Usage

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

2.0.4

7 years ago

2.0.3

7 years ago

2.0.2

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

2.0.0-beta3

7 years ago

2.0.0-beta2

7 years ago

2.0.0-beta1

7 years ago

2.0.0-beta0

7 years ago

1.0.1-beta0

7 years ago

1.0.0

7 years ago

0.1.0

7 years ago