2.0.2 • Published 4 months ago

redux-dispatcher v2.0.2

Weekly downloads
128
License
MIT
Repository
github
Last release
4 months ago

npm.io npm.io npm.io npm.io

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 }
2.0.2

4 months ago

2.0.1

5 months ago

2.0.0

5 months ago

1.9.9

7 months ago

1.9.8

2 years ago

1.9.7

2 years ago

1.9.84

2 years ago

1.9.83

2 years ago

1.9.82

2 years ago

1.9.81

2 years ago

1.9.6

3 years ago

1.9.5

3 years ago

1.9.4

3 years ago

1.9.3

3 years ago

1.9.2

3 years ago

1.9.1

3 years ago

1.9.0

3 years ago

1.8.0

3 years ago

1.7.2

3 years ago

1.7.1

3 years ago

1.7.0

3 years ago

1.6.1

3 years ago

1.6.0

3 years ago

1.5.3

4 years ago

1.5.2

4 years ago

1.5.1

4 years ago

1.5.0

4 years ago

1.4.6

4 years ago

1.4.5

4 years ago

1.4.4

4 years ago

1.4.3

4 years ago

1.4.2

4 years ago

1.4.1

4 years ago

1.4.0

4 years ago

1.3.0

4 years ago

1.1.4

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago