npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-toolbelt-thunk

v3.1.11

Published

Redux thunk helpers for redux-toolbelt

Downloads

604

Readme

redux-toolbelt-thunk

A set of helper functions that extends redux-toolbelt for usage with redux-thunk.

TOC

Article

Read about redux-toolbelt and redux-toolbelt-thunkhere

Installation

First, you have to install the redux-thunk npm package:

npm i -S redux-thunk
# or
yarn add redux-thunk

And add it to redux's applyMiddleware:

applyMiddleware(thunk)

More info on it's installation can be found in the package's docs.

Then install the redux-toolbelt-thunk npm package and the redux-toolbelt npm package it depends on.

npm i -S redux-toolbelt redux-toolbelt-thunk
# or
yarn add redux-toolbelt redux-toolbelt-thunk

Import

You may import the functions you'd like to use using one of the two methods:

import {makeThunkAsyncActionCreator} from 'redux-toolbelt-thunk'
// or
import makeThunkAsyncActionCreator from 'redux-toolbelt/lib/makeThunkAsyncActionCreator'

Motivation

makeAsyncActionCreator can be very useful to create an action creator that uses promises and reports its progress to the Redux state:

// Instead of:
const fetchUser = makeAsyncActionCreator('FETCH_USER')

dispatch(fetchUser('user_01'))
fetchUserFromServer('user_01')
  .then(result => dispatch(fetchUser.success(result)))
  .then(error => dispatch(fetchUser.failure(error)))

makeThunkAsyncActionCreator replaces these with one line:

const fetchUser = makeThunkAsyncActionCreator('FETCH_USER', fetchUserFromServer)
dispatch(fetchUser('user_01'))
// this dispatches the action: `{ type: 'FETCH_USER', payload: 'user_01' }`
// calls fetchUserFromServer
// when fetchUserFromServer's resolves, it calls `fetchUser.success` with the result.
// if fetchUserFromServer's fails, it calls `fetchUser.failure` with the error.

Usage

makeThunkAsyncActionCreator(baseName, asyncFn [,argsMapper[, options]])

Arguments

  • baseName - The name of the action, and prefixes of sub-actions created.

  • asyncFn - The function to execute when the action is called. It should return a Promise. When it resolves, it will trigger the success sub-action and if it rejects it will trigger the failure action.

    asyncFn will be called with the arguments passed to the action with the addition of the following arguments: {getState, dispatch, extraThunkArg}. extraThunkArg is explained here.

  • argsMapper - Maps the arguments that are passed to the action to the payload that will be used on the action dispatched when action is called and the meta that will be used when both the action and it's sub-actions are called.

  • options

    • prefix - Defaults to ''.

      Prefixes the action and sub-action name. Mostly useful with makeThunkAsyncActionCreator.withDefaults that will be described below.

    • defaultMeta - Defaults to undefined.

      Adds metadata to the action and sub-actions:

      const getUserFromServer = userId => Promise.resolve({id: userId})
      
      const fetchUserAction = makeAsyncThunkActionCreator(
        'FETCH_USER', //
        getUserFromServer,
        {defaultMeta: {ignore: true}}
      )
      
      fetchUserAction('01', {log: true})
      // {
      //   type: 'FETCH_USER',
      //   payload: '01',
      //   meta: {
      //     debug: false,
      //     log: false,
      //     _toolbeltAsyncFnArgs: ['user_01', {log: true}]
      //   }
      // }
    • argsMapper - Defaults to const trivialArgsMapper = (payload, meta) => ({payload, meta})

      Same as the argsMapper argument described above. The argument takes priority over the option.

    • ignoreOlderParallelResolves - Defaults to false

      If several promises are made before any of them resolves, you can choose to ignore older resolves and only receive the last one by passing true to this option

      const getUserFromServer = userId => Promise.resolve({id: userId})
      
      const fetchUserAction = makeAsyncThunkActionCreator(
        'FETCH_USER',
        getUserFromServer,
        {ignoreOlderParallelResolves: true}
      )
      
      fetchUserAction('01') //<-- ignore this promise
      fetchUserAction('02') //<-- ignore this promise
      fetchUserAction('03')

      Promises can be ignored not only by the action name but also by meta id (helpful when sending multiple requests using the same action)

      const getUserFromServer = userId => Promise.resolve({id: userId})
      
      const fetchUserAction = makeAsyncThunkActionCreator(
       'FETCH_USER',
       getUserFromServer,
       {ignoreOlderParallelResolves: true}
      )
      
      fetchUserAction('01', {id: 'user 01'}) //<-- ignore this promise
      fetchUserAction('01', {id: 'user 01'})
      fetchUserAction('02', {id: 'user 02'}) //<-- ignore this promise
      fetchUserAction('02', {id: 'user 02'})

Returns

An action creator that when called and dispatched, it will:

  • Dispatch an action with the type of baseName and payload and meta that are based on the arguments of the call, possibly mapped via argsMapper, if present.
  • Call the asyncFn and wait on the Promise it should return.
  • If it resolves, the success sub-action is dispatched with the result of the Promise.
  • If it rejects, the failure sub-action is dispatched with the error of the Promise.

_toolbeltAsyncFnArgs

This property is always added to the meta of every action and sub-action that are created with thunkAsyncActionCreator and reflects the arguments that it was called with.

const fetchUser = makeThunkAsyncActionCreator('FETCH_USER', fetchUserFromServer)
console.log(fetchUser('00'))
// {
//   type: 'FETCH_USER',
//   payload: ['00'],
//   meta: { _toolbeltAsyncFnArgs: ['00'] }
// }

withDefaults

Creates an instance of makeThunkAsyncActionCreator with the specified options:

const userMakeThunkAsyncActionCreator = makeThunkAsyncActionCreator.withDefaults({
  prefix: 'USER@',
  defaultMeta: {log: true},
  argsMapper: (...args) => ({payload: args})
})

const fetchUser = userMakeThunkAsyncActionCreator('FETCH_USER', fetchUserFromServer)
console.log(fetchUser.TYPE)
// 'USER@FETCH_USER'

console.log(fetchUser('00'))
// {
//   type: 'USER@FETCH_USER',
//   payload: ['00'],
//   meta: {
//     log: true,
//     _toolbeltAsyncFnArgs: ['00']
//   }
// }

console.log(fetchUser.success({id: 'user00'}))
// {
//   type: 'USER@FETCH_USER@ASYNC_SUCCESS',
//   payload: {
//     id: 'user00'
//   },
//   meta: {
//     log: true,
//     _toolbeltAsyncFnArgs: ['00']
//   }
// }