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

v0.8.8

Published

Redux side effects middleware

Downloads

4

Readme

Redux Butterfly

Side effects middleware for Redux.

npm version npm downloads

npm install redux-butterfly

or

yarn add redux-butterfly

Attention

If you use Butterfly in CommonJS environment, don’t forget to add .default to your import

const butterfly = require('redux-butterfly').default

What this does?

This library acts similary to redux-thunk

Its a middleware which alows you to use action creators which return a function. This function recieves set of enhancments. Those enhancments are then available on action creator. More on that below. Additionaly, if you return promise as a key named payload in your action. Butterfly will automaticaly dispatch start, success, and error actions for you.

Why this silly name? Because butterflies

Usage

import { applyMiddleware, createStore } from 'redux'
import butterfly from 'redux-butterfly'

import rootReducer from './reducers'

const config = {
  enhancers: {
    statics, // default: {}
    dynamics, // default: {}
  },
  enums: {
    start: START, // default: "START"
    success: SUCCESS, // default: "SUCCESS"
    error: ERROR, // default: "ERROR"
  },
}

const store = createStore(
  reducers,
  devToolsEnhancer(),
  applyMiddleware(butterfly(config), ...othermidlewares)
)

You may notice two config keys.

enhancers - this is where your enhancers will go

enums - define enum values for actions. MW will dispatch ACTION_TYPE_{value} for you automaticaly.

Enhancers

Enhancers are functions which are provided to the function returned by the action creator. There are two types: statics and dynamics

statics looks like this:

someValue => console.log(someValue)

dynamics:

(store) => store.someValue
(store) => (value) => `${store.someValue}_${value}`

As you can see - dynamic enhancment gets a redux store as an input parameter, then its up to you what you want to do with it. For example you can have function which makes an API calls and always takes user token from the redux store. This function is then available in action creator.

Action creator

const api = store => url =>
  fetch(url, {
    headers: {
      Authorization: store.session.token,
    },
  })

Then pass it to mw as a dynamic enhancer and use it in action creator

export const logIn = (username, password) => ({ api }) => ({
  type: LOG_IN,
  payload: api('http://example.com'),
})

If you dont pass payload (or you do, but its not a promise), or your action creator doesnt return a function, butterfly simply passes the action into next middleware.

And since you can pass promise to payload, you can use async action as a value of a payload and await complex api calls there, to avoid thunk promise chain hell.

Typescript

import { ButterflyAction, ButterflyProps, ButterflyResult } from './types'

interface Store {
  auth: { token: string}
}

interface User {
  name: string
  age: number
  token?: string
}

enum ActionTypes {
  GET_USER = 'GET_USER',
  GET_USER_SUCCESS = 'GET_USER_SUCCESS'
}

interface UserActionMeta {
  token: string
}


const getUser = (id: string) => ({ getState, logger }: ButterflyProps<Store>): ButterflyAction => {
  const { auth: { token } } = getState()
  return {
    type: 'GET_USER',
    payload: fetch('some_url', { headers: { authorization: token }}).then(res => res.json()),
    onSuccess: (data: User) => logger(data),
    token,
  }
}

const reducer = (state: Store, action: ButterflyResult<ActionTypes, User, UserActionMeta>) => {
  switch (action.type) {
    case ActionTypes.GET_USER_SUCCESS:
      return {
        ...action.payload,
        token: action.rest.token
      }

    default:
      return state
  }
}