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

@workpop/optimistic-middleware

v2.0.0

Published

Optimistic Methods Middleware for Redux

Downloads

9

Readme

Optimistic Middleware

Optimistically apply actions that will be reverted on error.

Installation

npm install --save @workpop/optimistic-middleware

import { optimisticMiddleware } from '@workpop/optimistic-middleware';

Usage

Step 1: Create your Reducer

Optimistic updates require your reducer to have a certain state shape.

type OptimisticStateType = {
    data: any,
    optimisticState: string
}
function todos(state = {}, action = {}) {
    const { type, data, ...rest } = action;
    switch(type) {
        case 'ADD_TODO':
            const todos = state.data;
            return {
                data: todos.concat([data.text]),
                ...rest
            };
        default:
            return state;
    }
}

Step 2: Build your Action Creator

Generic Optimistic Action Creator

function optimisticAddTodo(text) {
    return {
        simulate: {
            type: 'ADD_TODO',
            data: text,
        },
        stateKey: 'todos',
        async(cb) {
            return Meteor.call('addTodo', text, cb);
        }
    }
}

Functional Simulation

the simulate function will allow you to customize your simulations.

function optimisticAddTodo(text) {
    return {
        simulate(dispatch, data) {
            dispatch({
               type: 'ADD_TODO_ID',
               data: _.get(data, '_id');
            });
            return dispatch({
                type: 'ALL_TODOS',
                data
            });
        }
        stateKey: 'todos',
        async(cb) {
            return Meteor.call('addTodo', text, cb);
        }
    }
}

Custom Errors

function optimisticAddTodo(text) {
    return {
        simulate: {
            type: 'ADD_TODO',
            data: text,
        },
        onError(dispatch, prevState, error) {
            if (error.reason === 'you suck') {
                dispatch({
                    type: 'TODO_ERROR',
                    data: error.reason
                }); 
            }
            
            return dispatch({
                type: 'ADD_TODO',
                data: prevState
            });
        }
        stateKey: 'todos',
        async(cb) {
            return Meteor.call('addTodo', text, cb);
        }
    }
}

Custom onSuccess

function someThunk(result) {
    return (dispatch) => {
        someOtherAsync(result,(e, result) => {
            if (e) {
                console.error('ERROR');
            }
            dispatch({
                type: 'TOGGLE_TODO_LIST',
                data: result
            });
        });
    }
}
function optimisticAddTodo(text) {
    return {
        simulate: {
            type: 'ADD_TODO',
            data: text,
        },
        onSuccess(dispatch, result) {
            dispatch(someThunk(result));
        },
        stateKey: 'todos',
        async(cb) {
            return Meteor.call('addTodo', text, cb);
        }
    }
}

Let's break down our action shape:

type OptimisticActionType = {
    simulate: {
        type: string,
        data: any
    }
    stateKey: !string,
    async: Function,
    onError: ?Function,
    onSuccess: ?Function,
}
type OptimisticActionSimulateFuncType = {
    simulate: Function
    stateKey: !string,
    async: Function,
    onError: ?Function,
    onSuccess: ?Function,
}

Parameters:

  1. [simulate] - object or function to handle simulation. type/data if object, if function dispatch, data
  2. [stateKey] - key of reducer related to action
  3. [async] - asynchronous function intended to make mutation/remote call to the server
  4. [onSuccess] - function to be called when async function returns *optional
  5. [onError] - function to be called when the async function returns an error *optional

How this works:

When you dispatch an OptimisticAction, the action is intercepted by Redux middleware. Immediately we save the previous state of the passed in stateKey in case our action throws an error.

We start the dispatch process immediately executing the data change in the action to the reducer. From there, we call our asynchronous method.

If the method returns an error, we append several pieces of meta data with the error reason.

type OptimisticErrorType = {
   data: any
   type: string
}

Caveats

Because we are reverting our state when errors occur based on the reducer state, this middleware is confined to the reducer stateKey passed into the action. Optimistic Middleware does not currently support updates that affect multiple stateKeys.