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 🙏

© 2025 – Pkg Stats / Ryan Hefner

redux-ecq

v1.0.12

Published

Library for managing backend queries, commands and entities

Downloads

28

Readme

redux-ecq

E for Entity: an entity is a business object that has identity in the domain which we are building a front-end for. Typically, in any real-world application, a business domain can be seen as a collection of entities that refer to each other by identity.

C for Command: a call to a remote backend to modify the state of that backend, to execute a side-effect that changes the state of the world, e.g. place an order on an e-store, triggers a shipment ... etc.

Q for Query: On the other side, a query is a call to a remote backend to retrieve data without changing anything.

Redux ECQ is a Typescript front-end library that allows TS developers to define and run commands and queries while managing all the involved state, including query / command execution states and the state of data entities imported from queries or updated by commands. The library helps bring the following merits to front-end applications while alleviating the extra boilerplate code and indirection typically required to achieve that.

Reactive-Readiness

Redux ECQ leverages Redux to allow for building promise-free data-fetching React components, ones that are agnostic to the patterns of communication with a backend (request-reply or push-based). A reactive component is one that does not "ask" for data but instead "tells", or fires requests for data and continues reacting to state changes as data arrives back.

Normalized State of Front-end Data

Have you ever run in a situation where an entity view updates entity data while another view still holds the old values (e.g. updating the user's profile photo while the navbar still has the old one) ? we run into these issues often and this is a primary reason for using global state management libraries like Redux.

In Redux documentation, the author recommends keeping data entities in a normalized state shape. Actually, this library has been inspired by Dan's "normalizr" library, but unlike "normalizr", which only provided methods for normalizing / denormalizing payloads, this library takes full care of entity management transparently. When a caller invokes a query, the library normalizes the results payload into a redux store and keeps a denormalized copy for binding to React components. The redux reducer takes care of synchronizing entities with denormalized views and it takes care of cleaning up entities that are not used by active / mounted views.

Getting Started

Installation

You can install the library using npm (or yarn if that's your preference):

npm install --save redux-ecq

This library is a typescript-first library, there is no need for installing any typings.

Usage

The Entity Model

To make use of the library, there is a corner stone object that has to be created, which is the entity model of the data the UI is dealing with. Typically, in every front-end application, there is an implicit mental model for the data, what kind of objects the UI is dealing with, the fields of information each contains and how objects relate to each other. We're going to make that model explicit by defining the following entity model for a fictuous shipment management application:

(let's have that model in a separate file since we'll be importing it from different places)

my_domain.ts

import { 
    jsEntity, 
    jsString,
    jsNumber,
    jsDateTime,
    jsRef,
    DenormalizedType
} from "redux-ecq";

export const entityModel = {
    shipment: jsEntity({
        id: jsString(),
        weight: jsNumber(),
        deliveryDate: jsDate(),
        shipper: jsRef("customer"),
        consignee: jsRef("customer")
    }, "id"),

    customer: jsEntity({
        accountId: jsString(),
        name: jsString()
    }, "accountId")
}

// Optionally, you can use DenormalizedType<> to compute the denormalized shape of an entity for using in your application. That saves you from the additional boilerplate of re-defining the above entities as Typescript types
export type Shipment = DenormalizedType<typeof entityModel, "shipment">
export type Customer = DenormalizedType<typeof entityModel, "customer">

** Please note that we are primarily concerned with objects that have identity, which we'll refer to as entities.

Our First Query

This library adopts and encourages the usage of React hooks for managing all sorts of side-effects (commands and queries are side-effects). The following code creates a hook from a backend query that we will define:

my_queries.ts

import { queryHook } from "redux-ecq";
import { entityModel } from "./my_domain.ts"  // our entity model


interface ShipmentFindReq {
    shipmentId: string
}

export const useShipmentFinder = queryHook(entityModel, "shipment", (req:ShipmentFindReq) => {

    // this is an application defined callback to serves data from the backend in a denormalized shape adhering to the entity model
    // defined before. Replace the following with your real code that calls a remote backend and transforms the returned data into our domain's language

    return Promise.resolve({
        total: 2, 
        results: [
            {
                id: "1",
                weight: 45,
                deliveryDate: new Date(2022, 11, 1),
                shipper: {
                    accountId: "acc3",
                    name: "Mary Jane"
                },
                consignee: {
                    accountId: "acc1",
                    name: "John Doe",
                },

            },
            {
                id: "2",
                weight: 23,
                deliveryDate: new Date(),
                shipper: {
                    accountId: "acc3",
                    name: "Mary Jane"
                },
                consignee: {
                    accountId: "acc1",
                    name: "John Doe",
                }
            }
        ]
    });
});

my_component.ts

import { useShipmentFinder } from "./my_queries";


const ShipmentSearchPanel = ({ }) => {

    const [queryState, find] = useShipmentFinder({ shipmentId: "111" });
    
    return (
        <div>
            {queryState.data.map(i => (<Shipment id={i.id} consigneeName={i.consignee.name} /* ... */ />))}
        </div>
    )
}

Out First Command

Commands are actions that change data. The results of a command is one or changes to the entities affected by that command. We are going to write a sample / fictuous command that renames a customer account.

my_commands.ts

import { commandHook } from "redux-ecq";
import { entityModel } from "./my_domain.ts"  // our entity model


interface CustomerUpdateCommand {
    customerId: string
    newName: string
}

const useCustomerUpdater = commandHook(entityModel, (applyChanges) => 
    (cmd:CustomerUpdateCommand) => {

        // replace this with an actual backend call that returns a promise
        const backendCall = Promise.resolve({
            // Ideally, commands are one-way, but practically, in real world, sometimes backend commands are designed to return newly created IDs or other values. Result is the actual result that will go back to the 
            // ...
        });

        return backendCall.then(res => {
            // a call to this method will apply changes to concerned entities and dependent views will re-render accordingly
            applyChanges({
                modified: {
                    customer: {
                        [cmd.customerId]: {
                            name: cmd.newName
                        }
                    }
                }
            });
            // return expected response from command - if there is any
            return res;
        })
});

my_customer_update_form.ts

import { useCustomerUpdater } from "./my_commands";


const CustomerUpdateForm = ({ customerId, oldName, onCustomerUpdated }) => {

    const [newName, setName] = useState<string>(oldName);

    const [commandState, updateCustomer] = useCustomerUpdater();
    
    useEffect(() => {
        if (commandState.success) {
            onCustomerUpdated({ customerId: ...,  });
        }

    }, [commandState.success, newName]);

    return (
        <form onSubmit={ () => updateCustomer({ newName, customerId }) }>
            <input type="text" value={newName} onChange={setName} />
            <button type="submit">Save</button>
        </form>
    )
}