react-redux-dispatch-async
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

npm version

react-redux-dispatch-async

A redux middleware to be able to wait async actions (ie. side effects) with fixed defined suffixes.

                                     +------------------+
                              +----->+ ACTION_SUCCEEDED +
                              |      +------------------+
      +------------------+    |
      + ACTION_REQUESTED +----+
      +------------------+    |
                              |      +------------------+
                              +----->+  ACTION_FAILED   +
                                     +------------------+

Install

yarn add react-redux-dispatch-async

Examples

Configuration

import { createStore, applyMiddleware } from 'redux'
import { createDispatchAsyncMiddleware } from 'react-redux-dispatch-async'
import reducers from 'reducers'

const store = createStore(
  reducers,
  applyMiddleware(
    createDispatchAsyncMiddleware({
      request: 'REQUEST', // 👈 define your own async suffixes
      success: 'SUCCESS',
      failure: 'FAILURE',
    }),
  ),
)

Usage

import React from 'react'
import { useDispatchAsync } from 'react-redux-dispatch-async'

export default function MyUserInterface({ id }: { id: string }) {
  const { status, result, error } = useDispatchAsync(getUser, [id])

  switch (status) {
    case 'loading':
      return <AppLoader />
    case 'error':
      return <Text>{error.message}</Text>
    case 'success':
      return <User {...result} />
    default:
      return null
  }
}

Default suffixes

  • [...]_REQUESTED
  • [...]_SUCCEEDED
  • [...]_FAILED

Two functions

Configuration

dispatchAsyncMiddleware: (c?: {
  request: string
  success: string
  failure: string
}) => redux.Middleware

Type

// main hook
type useDispatchAsync = <R = any>(
  actionFunction?: (...args: any[]) => Action<T>,
  deps: any[] = [],
) => UseDispatchAsync<R>

/// return type
export interface UseDispatchAsync<R = any> {
  status: 'loading' | 'success' | 'error'
  result?: R
  error?: Error
}

// other types for oldest usage
interface DispatchAsyncResultSuccess<T = any> {
  success: true
  result: T
}
interface DispatchAsyncResultError {
  success: false
  error: Error
}
export type DispatchAsyncResult<T = any> =
  | DispatchAsyncResultSuccess<T>
  | DispatchAsyncResultError

Package Sidebar

Install

npm i react-redux-dispatch-async@1.0.0

Version

1.0.0

License

MIT

Unpacked Size

37 kB

Total Files

14

Last publish

Collaborators

  • xcarpentier