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

reduck

v0.2.2

Published

Opinionated way to create reducers and action creators

Downloads

18

Readme

reduck

build dependencies devDependencies

Opinionated way to create reducers and action creators.

  • Unlocks some specifically designed tooling (eslint-plugin-duck) to speed up the development process by catching as early as possible potential errors
  • Reduce the boilerplate

Ducks are a modular way to keep your redux action creators and reducers in the same place, simplifying the repo's structure and the development process. Some explanation on why this is beneficial can be found here and here.

Installation

  npm install --save reduck

Usage

actions.js

// We define our action types here so that they can easily be used by different ducks
export const FETCH_TODOS = 'todo.FETCH_TODOS';
export const ADD_TODO = 'todo.ADD_TODO';
export const LOGOUT = 'auth.LOGOUT';

ducks/todos.js

import Duck from 'reduck'

import {
  ADD_TODO,
  FETCH_TODOS,
  LOGOUT,
} from '../actions'

// define an initial state to use in the Duck's initialization
const initialState = {
  items: [],
  ready: false
};

const duck = new Duck('todo', initialState);

export const addTodo = duck.defineAction(ADD_TODO, {
  creator(newTodoItem) {
    return {
      payload: { newTodoItem }
    };
  },
  reducer(state, { payload }) {
    return {
      ...state,
      items: (state.items || []).concat(payload.newTodoItem)
    }
  }
})

// action defined in another duck but this duck still wants to react to it
duck.addReducerCase(LOGOUT, {
  reducer() {
    return initialState;
  }
})

export default duck.reducer

ducks/auth.js

import Duck from 'reduck'
import { LOGOUT } from '../actions'

const initialState = {
  user: {},
  authStatus: 'Unknown'
}

const duck = new Duck('auth', initialState);

duck.defineAction(LOGOUT, {
  creator() {
    return {} // Data is not necessary in this case
  },
  reducer(state) {
    return initialState
  }
})

export default duck.reducer;

reducer.js

import { combineReducers } from 'redux'

import auth from './ducks/auth'
import todos from './ducks/todos'

export default combineReducers({
  auth, todos,
})

API

constructor(duckName, initialState)

  • duckName: Given name of the duck
  • initialState: the state that the duck will be initialized with
  • returns a 'duck' object that provides the following methods:

Methods

defineAction(actionType: String, reducerCases: Object)

  • actionType is the type of the action. Can be whatever you choose as long as it follows the format: <duck-name>/<some-action-name>. This helps with tracking defined actions in each duck.

  • reducerCases consist of:

    • creator(actionArgs) The creator accepts any arguments related to the action being performed and then returns the object that will be passed to the action's reducers. The object consists of mainly payload (the payload that will be handled by the reducers) and meta (data that will be used by middleware). _Note:_The creator must be present in the defineAction method.
    • reducer(state, { payload }) The reducer function receives the payload sent by the creator and the duck's current state. It then calculates the next state and returns it.

Note: The API allows for more cases to be added at your convenience. An example of such cases is discussed further in the Middleware section.

addReducerCases(actionName: String, reducerCases: Object) This method is used similarly to defineAction but does not define a new action. It is used to define a reducer which will change the duck's state when an action from a different duck is dispatched. Therefore the actionName needs to be of an existing action and the reducerCases cannot have a creator.

  • add a reducer case with the actionName parameter as '*'. This reducer case will be invoked on every action that is dispatched by the duck, and will be applied to the state. For Example :
duckProduct.addReducerCase('*', (state, action) => {
  return {
    ...state
    /* etc */
  };
});

Middleware

We recommend using reduck with the following two packages:

By adding these to your redux middlewares, you can easily define async server calls as well the reducer cases that should be called when the request returns data or gets rejected.

We define the server call by using a meta.promise key in our action creator. We then define resolve() and reject() reducer cases. Given the example above, a FETCH_TODOS action to get the user's stored Todos from the server would look like this:

ducks/todos.js

export const fetchTodos = duck.defineAction(FETCH_TODOS, {
  creator() {
    return {
      meta: {
        promise: {       // This is the api for redux-object-to-promise
          method: 'GET',
          url: '/todo'   // Host URL is defined when the store is instantiated so we can use just relative URLs here
        }
      }
    }
  },
  reducer(state) {
    return {
      ...state,
      ready: false,     // setting ready to false while we wait for the network response
    }
  },
  // This is called when the data comes back from the server
  resolve(state, {payload}) { // In this case the payload comes from the server, not from the action creator
    return {
      ...state,
      items: payload.data.items,
      ready: true
    }
  },
  // This is called when the request to server fails (for whatever reason)
  reject(state) {
    return {
      ...state,
      ready: true
    }
  }
});

redux-optimist-promise also provides us with another meta key that can be used to revert optimistic updates in case of a server request failure. Let's adjust our ADD_TODO method to include a call to the server in order to update the user's data in the DB as well:

ducks/todos.js

export const addTodo = duck.defineAction(ADD_TODO, {
  creator(newTodoItem) {
    return {
      payload: { newTodoItem }
      meta: {
        promise: {
          method: 'POST',
          url: 'todo',
          data: { item: newTodoItem }
        },
        optimist: true
      }
		}
  },
  reducer(state, { payload }) {
    return {
      ...state,
      items: (state.items || []).concat(payload.newTodoItem)
    }
	}
})

Normally, we would want to add a reject() function that would roll back the reducer's changes since the failed server call would mean our client and DB data would be out of sync. By using optimist: true in our meta fields however, the change will be automatically reverted if the server request fails!

License

MIT

Appropriate GIF

Duck!