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

v2.0.2

Published

All-in-one simple solution to manage actions with less code

Downloads

285

Readme

redux-dispatcher is an all-in-one simple solution to manage actions with less code 🦄

Its main purpose is to combine action type, action creator and dispatch function into one, then you no need to worry about defining and managing action type constants.

Short example

import { createDispatcher } from 'redux-dispatcher'

const key = "app"

const mapDispatch = {
    setUser: name => ({ name })
};

const appDispatcher = createDispatcher(key, mapDispatch)
appDispatcher.setUser("Anonymous")  // dispatch action {type: "app/SET_USER", name: "Anonymous"}

Guaranteed:

  • Intuitive
  • Less code

Suitable:

  • If you use Redux and want to reduce boilerplate
  • If you find it tiresome every time you need to define, import, manage actions

Advanced functionalities:

Usage

1. Install and setup

npm install redux-dispatcher --save

Setup

import {applyMiddleware, createStore} from "redux";
import {dispatcherMiddleware} from "redux-dispatcher";

const store = createStore(
    reducer,
    applyMiddleware(dispatcherMiddleware)
);

2. Define action type, action creator and dispatch action

With redux-dispatcher, the action type is implicitly computed according to the key passed to createDispatcher method and the name of the action creator.

But if you want to explicitly specify a type, you can include a type property in the return object.

import { createDispatcher } from 'redux-dispatcher';

const key = "profile";

const mapDispatchToAC = {
    // type = "profile/FETCH_PROFILE"
    // if the action doesn't depend on parameters, you can just write a plain object
    fetchProfile: {loading: true},

    // if not explicitly specified, the action type will be automatically set: type = "profile/UPDATE_PROFILE"
    updateProfile: (username, password) => ({
        // type: "UPDATE_PROFILE",     you can specify the action type here
        username, password
    })
};

const profileDispatcher = createDispatcher(key, mapDispatchToAC);

To dispatch action, you can just import the dispatcher you need and dispatch action anywhere you want

profileDispatcher.updateProfile("my_username", "my_password");

3. Handle action in reducer

Create reducer with redux-dispatcher is as easy as create a usual reducer, with less code.

import { createReducer } from 'redux-dispatcher';

const mapActionToReducer = () => ({
     // similar to fall-through case in switch statement
     [[
       profileDispatcher.fetchProfile,
       profileDispatcher.reloadProfile,
       profileDispatcher.resetProfile
     ]]: (state, payload) => payload,    // notice the payload, it doesn't have "type" property like action
     
     [profileDispatcher.loadingProfile]: {loading: true},    // you can just write a plain object if new state doesn't computed from current state or action payload
     
     [profileDispatcher.updateProfile]: (state, {username, password}) => ({
       username,
       password: encrypt(password)
     })    // only return what data need to be merged in state
     
     // the default case is handled automatically
})

const profileReducer = createReducer(initialState, mapActionToReducer);

const rootReducer = combineReducers({
  profile: profileReducer,
});

4. Advanced functionalities

This section describes some useful features and extensions you may find interesting like thunk and immutable helper.

Retrieve side effect result after dispatching an action

(Available from v1.9.6)

See example.

Use case with React:

const mapDispatchToAC = {
 fetchProfile: userId => ({ userId }),
};

const userDispatcher = createDispatcher('user', mapDispatchToAC);
// Component A
async componentDidMount() {
 const action = userDispatcher.fetchProfile(userId)
 const profile = await action.waitResult()
 // profile = { name: "Emily" }
}

In your side effect handler (example with Redux Saga):

import { take } from 'redux-saga/effects'

function* fetchProfile(action) {
 const profile = { name: "Emily" }   // call your side effect here (like API request)
 action.dispatchResult(profile)
}

function* sagaWatcher() {
 yield take(userDispatcher.fetchProfile, fetchProfile)
}

If you want to subscribe for result from other places:

// Component A calls userDispatcher.fetchProfile
// but Component B and Component C also want to subscribe for the action's result

import { waitResult } from "redux-dispatcher";

// Component B
async componentDidMount() {
 // this Promise will be resolved when dispatchResult is called.
 // if dispatchResult has already been called before, this waitResult will immediately return a cached result
 const result = await waitResult(userDispatcher.fetchProfile)
}

// Component C
componentDidMount() {
 const unsubscribe = waitResult(userDispatcher.fetchProfile, result => {
  // each time dispatchResult is called, this callback will be triggered
 })

 // to remove the callback from listening to result, simply call unsubscribe()
}

// in Component A, you can also subscribe for continuous results like in Component C
componentDidMount() {
 userDispatcher.fetchProfile(userId).waitResult(result => {
  // each time dispatchResult is called, this callback will be triggered
 })
} 

Define thunk like your favourite Redux Thunk

const mapDispatchToAC = {
 fetchUser: id => ({dispatch, getState, context}) => {
  // do something
 }
}

You can also provide global context to dispatcherMiddleware just like how Redux Thunk middleware inject custom arguments, read more.

import {dispatcherMiddleware} from "redux-dispatcher"

const context = {
 BASE_API_URL,
 FetchHelper
}

const store = createStore(
        reducer,
        applyMiddleware(dispatcherMiddleware.withContext(context))
)

// reducer
const mapActionToReducer = context => {

}

Immutable helpers for state

const profileReducer = createReducer(initialState, {
 /* equivalent to:
    case "profile/UPDATE_STREET":
       return {
         ...state,
         userInfo: {
           ...state.userInfo,
           address: {
             ...state.userInfo.address,
             street: action.street
           }
         }
       }
 */
 [profileDispatcher.updateStreet]: (state, {street}, {set}) => ({
  street: set('userInfo.address.street', street)
 })
});

All immutable helper functions are based on dot-prop-immutable

[profileDispatcher.updateStreet]: (state, payload, {get, set, merge, toggle, remove}) => ({

})

Easily manage action types

profileDispatcher.key === "profile"    // true
profileDispatcher.updateProfile.type === "profile/UPDATE_PROFILE"    // true

/* equivalent to:
   const handler = {
      "profile/UPDATE_PROFILE": (state, payload) => {}
   }
*/
const handler = {
 [profileDispatcher.updateProfile]: (state, payload) => {}
} 

An example when working with Redux Saga: Instead of passing an action type, you can just pass a dispatcher function to the takeLatest function.

const action = yield take(profileDispatcher.updateProfile)
// action = { type, username, password }