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

v0.2.0

Published

Reusable redux data structures

Downloads

13

Readme

redux-strucures

Reusable idiomatic redux data structures.

npm version Open Source Love

npm install --save redux-structures

Docs

Motivation

Redux applications often implement the same reducer logic. For instance, adding or removing a property from a state object, inserting an element to a list or updating a value. redux-structures provides reusable and encapsulated implementations of these common data structures, so that you do not have to rewrite the same reducers over and over.

To illustrate the problem, consider a chat application. The store has users and messages, which are both objects:

store.getState()
/*
{
  users: {
    1: { id: 1, name: 'john doe', ... }
    2: { id: 2, name: 'jane doe', ... }
    ...
  },
  messages: {
    1: { id: 1, text: 'hello, world', userId: 1, ...}
    2: { id: 2, text: 'what\'s up ?', userId: 2, ...},
    ...
  }
}
*/

Common actions include adding or removing a user, as well as adding or removing a message. Traditionally, the same logic is implemented in both reducers.

function users(state, action){
  switch(action.type){
    case ADD_USER: return {...state, [action.user.id]: action.user}
    ...
  }
}

function messages(state, action){
  switch(action.type){
    case ADD_MESSAGE: return {...state, [action.message.id]: action.message}
    ...
  }
}

Notice that the only difference between the two reducers are the constants and the action property names. The same error-prone logic is repeated.

redux-structures implements this logic once, and allows you to instantly create coupled reducer - action instances.

import { HashMap } from 'redux-structures'

const { reducer: users, actions: userActions} = HashMap('users')
const { reducer: messages, actions: messageActions} = HashMap('messages')

Now, to add a user, simply dispatch userActions.set(id, user). (Refer to the documentation for more information.)

This has several advantages.

  • Faster and safer development
  • You no longer need to unit-test individual reducers, since they tested once at the library level.

Concepts

redux-structures employs two core concepts.

  • Structures

    Structures are functions that return a reducer and actions. There are different types of structures: Value, HashMap, and List.

  • Instances

    Instances are reducer - actions pairs, obtained by calling a structure. Instances are created with a unique name, so that actions only affect the reducer to which they are bound. Actions and reducers are coupled, in that the reducer will only match actions created by the instance's action creators. In our example, an instance would be messages and messagesAction.

Patterns

redux-structures provides basic level operations, and does not get in the way of your application-specific needs. You can dispatch the actions from anywhere in your app - from the view, middleware, or thunk like you do with traditional actions.

Higher order action creators

You can define higher-order actions, which take a parameter and return another action creator. Consider what happens a user submits a new message, in the earlier example.

const { reducer: messages, actions: messageActions} = HashMap('messages')

const createMessage = text => {
  const id = generateId()
  const message = {
    text,
    sentAt: Date.now(),
    id
  }
  return messageActions.set(id, message)
}

Here, the create action returns another more general action creator.

Using middleware

Actions from redux-structures can be dispatched from anywhere, including middleware.

Composing reducers

You can define reducers which contain reducers from redux-structures.

Usage

It is recomended to export instances from their own module, like in traditional redux applications. Then, import all reducers when creating the store, and import actions where necesary.

messages.js

import { HashMap } from 'redux-structures'
const { reducer, actions } = HashMap('messages')

/* define custom actions, here with the thunk middleware */

function fetchMessage(id){
    return dispatch => {
        fetch(`/message/${id}`)
            .then(message => dispatch(actions.set(id, message)))
    }
}
function fetchMessages(){
    return dispatch => {
        fetch(`/messages`)
            .then(messages => {
                dispatch(actions.setAll(messages))
            })
   }
}

const messageActions = {
  ...actions,
  fetchMessage,
  fetchMessages
}

export { messageActions }
export default reducer

index.js

import { createStore, combineReducers } from 'redux'
import messages from './path/to/messages'
import users from './path/to/users'

export default createStore(
  combineReducers({
    messages,
    users
  })
)

view.js

import { messageActions } from './path/to/messages'

/* import actions and dispatch as you wish */