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

v1.0.0

Published

(Redux Middleware) Dispatch async action listener at any time and do side effect for Redux

Downloads

36

Readme

redux-listener

Dispatch async action listener at any time and do side effect for Redux.

Installation

$ npm install --save redux-listener

Usage

import { createStore, applyMiddleware } from 'redux';
import { createListenerMiddleware, on, attach } from 'redux-listener';
import rootReducer from './reducers';

const reduxListenerMiddleware = createReduxListenerMiddleware();
const store = createStore(
  rootReducer,
  applyMiddleware(createListenerMiddleware)
);

async function someFunction() {
  // 'on' is a plain action creator to help to add the listenr
  store.dispatch(on('ASYNC_MESSAGE', (action, { dispatch }) => {
    return new Promise(resolve => {
      setTimeout(() => {
        console.info('');
        resolve();
      }, 1000);
    });
  }));

  store.dispatch({
    type: 'INCREMENT_ASYNC',
  });

  const result = await attach(store.dispatch({
  }))
}

Concepts

The basic concept of redux-listener is

Do dispatch(async listener) for redux action at any time.

To archive this, there are serveral advanced concepts that are designed.

1. Action listener is only for side effect, so the original redux data flow shouldn't be interrupted.

// Chart

2. Register async action listener on demand for any plain redux action.

Eazy to do code splitting. Just dispatch and add required async action listeners before business logic.

3. For one action type, only one listener is allowed.

Easy to make test. You can mock and override any exist listener to test.

So there are only on(type, listener) and off(type, listener), and no addListener and removeListener in order to avoid misunderstanding.

However multiple listeners can be composed as one listener for one action type.

There is an example.

import { query, on, attach } from 'redux-listener';

async function someFunction() {
  const existListener = await attach(dispatch(query('SOME_ACTION_TYPE')));
  dispatch(on('SOME_ACTION_TYPE', async (action, ...args) => {
    // do something
    const originalResult = await existListener(action, ...args);
    // do something
    return originalResult; // Or something else
  }));
}

4. The async listener should be waitable.

For chaining multiple async action.

async function someFunction() {
  await attach(dispatch({
    type: "ASYNC_FETCH_SCHOOL_REQUEST",
    payload: {
      schoolId: 3
    }
  }));

  const school = selectSchool(getState(), 3);
  const classroomIds = school.classrooms;

  const classroomPromises = classroomIds.map((id) => {
    return attach(dispatch({
      type: "ASYNC_FETCH_CLASSROOM_",
      payload: {
          classroomId: id
      }
    }));
  });

  await Promise.all(classroomPromises);
  // ...
}

5. dispatch(), getState() and other extra arguments are available as same as redux-thunk.

But take care of dispatching actions inside the async listener, it may cause infinite loop!!

INSTALLATION

For npm

npm install --save redux-listener

For yarn

yarn add redux-listener

API

createListenerMiddleware([extraArgument])

Create a new listener middleware with extra argument.

const store = createStore(
  reducer,
  applyMiddlware(createListenerMiddleware({ api, whatever })),
);

store.dispatch(on('TYPE_OF_ACTION', async (action, dispatch, getState, { api, whatever }) => {
}));

on(type, listener)

Adds an action listener for type. The value returned by listener can be accessed by attach() function.

store.dispatch(on('TYPE_OF_ACTION', async (action, dispatch, getState, extraArgument) => {
  // ...
}));

Arguments

  • type ( String ): Action type.
  • listener(action, dispatch, getState, extraArgument): Promise or any ( Function ): Listener for specified action type. The dispatched action, dispatch, getState, extraArgument will be passed. Promise is recommended returned type, since the result can be accessed by attach().

off(type)

Removes an action listen for type.

store.dispatch(off('TYPE_OF_ACTION'));

An action creator that is used to remove the listener for type.

query(type)

An action creator that is used to query the registered listener for type. Use attach(result) to access the returned listener.

async function example() {
  const result = store.dispatch(query('TYPE_OF_ACTION'));
  const listener = await attach(result);
}

You can use this function to delegate the exist listener.

attach(dispatchResult)

Attachs the listener of dispatched action and gets the result.

async function example() {
  store.dispatch(on('ACTION_TYPE_A', async (action, dispatch, getState, extraArgument) => {
    const { msg } = action.payload;
    return msg;
  }));

  const result = store.dispatch({
    type: 'ACTION_TYPE_A',
    payload: {
      msg: 'Hello'
    }
  });

  const listenerResult = await attach(result);
  console.info(listenerResult); // "Hello"
}

LICENSE

MIT