2.0.0-beta2 • Published 7 years ago

cached-effect v2.0.0-beta2

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

💥 React effect manager

NPM Version NPM Downloads GitHub issues Telegram

Manage effects in React using hooks. Create cached effects from async functions and handle them with useCache hook. Call your effects to update cache

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 a promise) in createEffect:

const myEffect = createEffect(async () => { /* do something */ })
// or
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, usersLoading] = useCache(fetchUsers)

useCache returns an array of [result, error, pending] which is equal to [undefined, null, false] by default.

Running effects

In order to populate the cache you need to run your effect. You can do it, for example, in useEffect hook inside of 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(payload) method

You can run your effect only once, for instance, when you have many components using this effect:

useEffect(() => {
  fetchUsers.once({ organizationId })
}, [])

usePending hook

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)

.use(handler) method

You can replace an async handler of your effect by using .use method. This is useful for mocking API calls, testing etc. Just pass a new handler to .use method:

fetchUsers.use(async () => {})

Tip

If you found this hook useful, please star this package on GitHub

Author

@doasync

Credits

This package was inspired by Effector library (from @ZeroBias). Effector is a reactive state manager, which has stores, events and effects as well as other useful features for managing state. It's also has effector-react package for React. This cached-effect package is currently not compatible with effector effects

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