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-observable

v3.1.15

Published

Epic helpers for redux-toolbelt

Downloads

4,352

Readme

Redux-Toolbelt-Observable

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

TOC

Article

Read about redux-toolbelt here

Installation

The tools are available in the redux-toolbelt-observable npm package.

npm install --save redux-toolbelt redux-toolbelt-observable rxjs redux-observable

# or

yarn add redux-toolbelt redux-toolbelt-observable rxjs redux-observable

Usage

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

import { makeAsyncActionCreator } from 'redux-toolbelt';
import { makeAsyncEpic } from 'redux-toolbelt-observable';

// or

import makeAsyncActionCreator from 'redux-toolbelt/lib/makeAsyncActionCreator';
import makeAsyncEpic from 'redux-toolbelt-observable/lib/makeAsyncEpic';

API Reference

makeAsyncEpic

makeAsyncEpic(asyncActionCreator, asyncFn, options?)

Creates an epic that handles actions created makeAsyncActionCreator.
The epic listens to the request action and dispatches success and failure actions.

Example

const fetchTodos = makeAsyncActionCreator('FETCH_TODOS');

const fetchTodosFromServer = () => {
  return axio.get('api/v1/todos');
};

const epic = makeAsyncEpic(fetchTodos, fetchTodosFromServer);

Arguments

asyncActionCreator

An async action creator created by makeAsyncActionCreator.

asyncFn

The async request to be executed. The function accepts the action's payload, type, meta and the store's state$ as parametes. It can return either an Object, a Promise or an Observable.

const fetchTodosAsyncFn = payload => {
  return axio.get(`api/v1/todos/${payload.id}`);
};

const createOrUpdateTodoAsyncFn = (payload, type, meta, state$) => {
  const isNew = !state$.value.todos.find(t => t.id === payload.id);
  return isEdit
    ? axio.put(`api/v1/todos/${payload.id}`, { data: payload })
    : axio.post(`api/v1/todos`, { data: payload });
};

const callMultipleApisAsyncFn = async () => {
  const first = await axios.get('api/v1/first');
  const second = await axios.get('api/v1/second');
  return { first, second };
};

Note: The reason for the asyncFn signature to break down the action into its pars payload, type, meta as opposed to accepting a single action parameter is to simplify a very common scenario where the following mapping is used:

const epic = makeAsyncEpic(actions.updateTodo, api.updateTodo);
actions.updateTodo({ id: 5, text: 'todo 5' });

Had the signature of the asyncFn would have been (action, state$) you would have had to change the epic to:

// WRONG - do not do this
const epic = makeAsyncEpic(actions.updateTodo, action =>
  api.updateTodo(action.paylod)
);

and repeat it again and again.

options

ignoreOlderParallelResolves (deprecating: cancelPreviousFunctionCalls)

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 fetchTodos = makeAsyncActionCreator('FETCH_TODOS');

const fetchTodosFromServer = payload => {
  /*...*/
};

const epic = makeAsyncEpic(fetchTodos, fetchTodosFromServer, {
  ignoreOlderParallelResolves: true
});

Payload and Meta

You can pass parameters within the ActionCreator like this:

const fetchTodos = makeAsyncActionCreator('FETCH_TODOS');

const fetchTodosFromServer = payload => {
  /*...*/
};

const epic = makeAsyncEpic(fetchTodos, fetchTodosFromServer);

fetchTodos(payload, meta);

After the request has returned successfully, the meta object contains the original meta and an object name _toolbeltAsyncFnArgs with the payload that was sent. For example:

// actions.js
const fetchAddFive = makeAsyncActionCreator('FETCH_ADD_FIVE')

// api.js
const fetchAddFiveFromServer = ({number}) => Promise.resolve(number + 5)

// epics.js
const epic = makeAsyncEpic(fetchAddFive, fetchAddFiveFromServer)

// execute action
fetchAddFive({number: 1}, {a: true})

// on request
{TYPE: 'FETCH_ADD_FIVE@ASYNC_REQUEST', payload: {number: 1}, meta: {a: true}}

// on success
{TYPE: 'FETCH_ADD_FIVE@ASYNC_SUCCESS', payload: 6, meta: {a: true, _toolbeltAsyncFnArgs: {number: 1}}}

This ability makes sure you use the most updated response.

makeSuffixesEpic

makeSuffixesEpic(mapper, suffixes, metaPredicate?)

export const errorInAsyncRequests = makePrefixesEpic(
  ({ payload }, _) => {
    if (payload.status === 401 || payload.status === 403) {
      return actions.reset();
    }
    return showSnack(
      payload?.error.message || payload.message || 'Unknown error'
    );
  },
  ACTION_ASYNC_FAILURE_SUFFIX,
  meta => meta.shouldIgnoreGlobalError
);

makeGlobalErrorEpic

makeGlobalErrorEpic(mapper)

Creates an epic that handles failure actions created by calls to makeAsyncActionCreator.
The helper epic listens to the all failure actions dispatched in the application and allows you to handler them centrally, in one place. A common usage of this epic is to show error messages/notifications/toast in a common way and controlled in a single place in the code.

export const errorInAsyncRequests = makeGlobalErrorEpic(
  ({ payload }) => ({ payload }, _) => {
    if (payload.status === 401 || payload.status === 403) {
      return actions.reset();
    }
    return showSnack(
      payload?.error.message || payload.message || 'Unknown error'
    );
  }
);