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-select-entities

v3.2.0

Published

Simple abstraction over normalizr and reselect to handle normalized entities

Downloads

196

Readme

redux-select-entities

build status codecov coverage npm

Light abstraction to use with normalizr to handle normalized entities, using higher-order-reducers.

Getting Started

Install redux-select-entities via npm:

$ npm install --save redux-select-entities

First, you'll want to create a reducer for one of your entities.

import { entityReducer } from 'redux-select-entities';

const todoReducer = (state, action) => {
    // the business logic you need to handle
};

const enhancedTodoReducer = entityReducer(todoReducer, options);

You can then, instead of using redux's combineReducers at the root of your reducers, use combineReducersWithEntities. It takes two parameters, first your entities reducers, and then your usual reducers.

import { createStore } from 'redux';
import { combineReducersWithEntities } from 'redux-select-entities';

const appReducer = combineReducersWithEntities(
    {
        todo: enhancedTodoReducer,
    },
    {
        // all your other reducers
        auth: authReducer,
        layout: layoutReducer,
    },
);
const store = createStore(
    reducer,
);

You now have a state which has the following shape:

{
    entities: {
        todo: {} // your normalized todos in a map
    },
    auth: authState,
    layout: layoutState,
}

This lets you use the select function to get any entity from your state. By calling select('todo', state, 1), you'll get the todo of id 1.

Usage

The most important part of the API is done by the entityReducer higher-order reducer. It takes a reducer and an optional option parameter (without any options, the higher-order reducer won't do anything for you beside initializing the state).

// No need to specify the default state, it will be done by the entitiesReducer
const todoReducer = (state, action) => {
    switch action.type: {
        case DELETE_TODO: {
            const {todoId} = action.payload;
            const newState = Object.assign({}, state);
            delete newState[todoId];
            return newState;
        }
    }
};
const enhancedTodoReducer = entitiesReducer(
    todoReducer,
    {
        actionTypes: ['GET_TODO'],
    },
);

const appReducer = combineWithEntitiesReducer({todo: enhancedTodoReducer});

const newState = appReducer(
    state,
    {
        type: 'GET_TODO',
        payload: normalize({ id: 1, content: 'be amazing' }, new schema.Entity('todo')),
    },
);

The enhanced reducer automatically normalized the todos for you, by returning a map containing the todos:

console.log(newState.entities.todo);
{
    1: { id: 1, content: 'be amazing' }
}

While the structure of the entities section of the state is public (any breaking change would mean a major semver bump), you are encouraged to use the select and selectAll functions to retrieve entities.

select('todo', newState, 1); // { id: 1, content: 'be amazing' }
selectAll('todo', newState); // { 1: { id: 1, content: 'be amazing' } }

selectAll is mostly useful if you need to retrieve some entities with something else than their id. For instance:

const todoMap = selectAll('todo', state);

// This gives you an array containing all the todos of the todoMap that are done
Object.values(todoMap).filter(
    (todo) => todo.done === true,
)

This kind of pattern works well with reselect's API, by letting you do things like:

const getConnectedUserTodos = createSelector(
    [
        selectAll('todo'),
        getConnectedUserId, // globalState => id
    ],
    // As long as neither the todos, neither the userId changes, the following function
    // won't be called
    (todoMap, userId) => Object.values(todoMap).filter(todo => todo.createdBy === userId),
)

API

entityReducer(reducer, options)

Takes first the reducer function, and an optional object to configure how the normalization behavior. The reducer function will be called for each action, as if it was not enhanced by entityReducer, but the state passed to the reducer will first pass through the higher-order reducer, where the normalization is handled.

Option Name | Type | Default | Description --------------------|--------------|--------------|-------------------------------- actionTypes | array | [ ] | the list of the actions where the reducer should search the normalized entities revive | function | | if set, each entity to normalize will pass through this function before being set in the state merger | function | merge | If an entity to normalize is already set in the state, the merger function will be called with first the entity from the state, then the one from the action, and finally the whole action. The return value of the function will be set in the state. normalizeIf | function | | Any action will pass through this function, if the function returns a truthy value, the content of the payload will be handled by the reducer. Doing normalizeIf: action => action.type === 'ADD_TODO' is equivalent to actionTypes: ['ADD_TODO']. This option is a way to programmatically determine which actions should be handled.

entityReducer does not return directly the enhanced reducer, but a function that take a single string parameter, that is the name used to declare the normalization schema (in this example, new schema.Entity('todo'), the name is 'todo). This function returns the enhanced reducer. Usually, you won't have to pass the name manually, since combineReducersWithEntities (through a call to createEntitiesReducer) takes care of it.

combineReducersWithEntities(entitiesReducerMap, reducerMap)

A wrapper around redux's combineReducers to create the main app reducer, that both handles the app's reducers, and the entities ones. The first parameter is an object litteral where each key is the name of an entity (see entityReducer doc) and the value the function returned by entityReducer. The second parameter is the map of the reducers, the one that would usually passed to combineReducers.

createEntitiesReducer(entitiesReducerMap)

A wrapper around redux's combineReducers to create the entities reducer. Its parameter is an object litteral where each key is the name of an entity (see entityReducer doc) and the value the function returned by entityReducer.

This function is exposed for people who don't want to bind the entities to the entities key of the state.

select(entityName, state, entityId) (this function is curried)

Returns the entity corresponding if it exists, null if it doesn't.

selectAll(entityName, state) (this function is curried)

Returns the map of entities corresponding.

customSelect(selectEntitiesState)

Takes a function returning the section of the state where the entities are stored. Return a method with the same signature and behavior than select. customSelect(state => state.entities)(...) is equivalent to select(...).

customSelectAll(selectEntitiesState)

Takes a function returning the section of the state where the entities are stored. Return a method with the same signature and behavior than selectAll. customSelectAll(state => state.entities)(...) is equivalent to selectAll(...).

selectWhere(entityName, where, state) (this function is curried)

Returns the entity whose id corresponds which equals where(state).