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

another-redux-manager

v4.0.0

Published

Yet another attempt to reduce boilerplate for async actions and reducers.

Downloads

1,848

Readme

Another Redux Manager

Yes yet another attempt to reduce boilerplate for redux whilst still keeping granular control over actions and reducers.

Why

  • Reduces boilerplate
  • No overblown middleware required
  • Less opinionated
  • plays nice with existing codebase (use as much or as little as your want)
  • More control over shape of your store and reducers

Dependencies

  • axios

Install

$ npm i another-redux-manager axios

Example


import { createReduxManager } from 'another-redux-manager';

// create a redux manager instance
export const getContentManager = createReduxManager('GET_CONTENT');

// example redux thunk which dispatches actions
export function getContent() {
  return dispatch => {
    dispatch(getContentManager.inProgress());

    return getContentManager.fetch({url: '/some-endpoint'})
      .then(data => {
        return dispatch(getContentManager.success(data));
      })
      .catch(error => {
        return dispatch(getContentManager.failure(error));
      });
  };
}

// example reducer
const INITIAL_STATE = {
  [getContentManager.name]: {
      status: getContentManager.actionTypes.initial,
      error: null
      results: null
    },
};

function contentReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    case getContentManager.actionTypes.initial:
        return getContentManager.reducerMethods.initial(state, INITIAL_STATE[getContentManager.name].results);
    case getContentManager.actionTypes.inProgress:
        return getContentManager.reducerMethods.inProgress(state, action);
    case getContentManager.actionTypes.success:
      return getContentManager.reducerMethods.success(state, action);
    case getContentManager.actionTypes.failure:
      return getContentManager.reducerMethods.failure(state, action);
    default:
      return state;
  }
}

NOTE: The default success reducer merges the results object with the data you fetch. If you require a full replace then use the advanced reducer configuration below.-

Getting Started

const contentReduxManager = createReduxManager({name: 'CONTENT'});

returns the following object:

{
  name:'CONTENT',
  actionTypes:{
    initial:'CONTENT_FETCH_INITIAL',
    inProgress:'CONTENT_FETCH_IN_PROGRESS',
    success:'CONTENT_FETCH_SUCCESS',
    failure:'CONTENT_FETCH_FAILED'
  },
  actionTypeKeys:{
    CONTENT_FETCH_INITIAL:'CONTENT_FETCH_INITIAL',
    CONTENT_FETCH_IN_PROGRESS:'CONTENT_FETCH_IN_PROGRESS',
    CONTENT_FETCH_SUCCESS:'CONTENT_FETCH_SUCCESS',
    CONTENT_FETCH_FAILED:'CONTENT_FETCH_FAILED'
  },
  actions: {
    initial: () => {...},
    inProgress: () => {...},
    success: () => {...},
    faulure: () => {...},
  },
  reducerMethods:{
    initial: () => {...},
    inProgress: () => {...},
    success: () => {...},
    faulure: () => {...},
  },
  initial: () => {...},
  inProgress: () => {...},
  success: () => {...},
  faulure: () => {...},
}

Access ActionCreators

const { initial, inProgress, success, failure} = contentReduxManager.actions;

or also available as shorthand references:

const { initial, inProgress, success, failure} = contentReduxManager;

Access Action types

const { initial, inProgress, success, failure } = contentReduxManager.actionTypes;
const { CONTENT_FETCH_INITIAL, CONTENT_FETCH_IN_PROGRESS, CONTENT_FETCH_SUCCESS, CONTENT_FETCH_FAILED } = contentReduxManager.actionTypeKeys; // plain action types

Access Reducer Methods (for use in your switch statement in your reducer)

const { initial, inProgress, success, failure} = contentReduxManager.reducerMethods; // reducer methods

You can also define multiple arguments to your actions (if you need to)

const contentReduxManager = createReduxManager({name: 'CONTENT', resultsPropsName: 'results' }, 'payload', 'anotherProp');

console.log(actions.inProgress({payload: 'test', anotherProp: 'test' }));
// { type: 'CONTENT_FETCH_IN_PROGRESS', payload: 'test', anotherProp: 'test' }

Usage

Create a redux helper

const contentReduxManager = createReduxManager({name: 'CONTENT', argNames: ['payload'], resultsPropsName: 'results', reducerMethods: () => {} });

Properties:

| prop | desc | |---|---| | name | unique prefix for actions and reducers (RECOMMENDED: all uppercase and separated by underscore to match async postfixes) | | argNames | array of argument names for actions (OPTIONAL: defaults to ['payload']) | | resultsPropsName | name of property in the reducer to place fetched data (OPTIONAL: defaults to ['results']) | | reducerMethods | function that allows customising of shape of reducer (OPTIONAL: see advanced usage) |

Call async http endpoint (axios)

const result = await contentReduxManager.fetch({query: '/some-endpoint'});

| prop | desc | |---|---| | type | 'POST', 'DELETE', 'PUT', 'PATCH' .. defaults to 'GET' | | logger | your choice of logging util. Must implement logger.error() method. Defaults to console.error | | config | axios config for post params, headers etc.. | | name | used when logging errors. outputs 'Fetch Failed |

Advanced Usage

by default the shape of each reducer method looks something like:

const makeReducerMethods = (reduxManager, resultsPropName) => {
  return {
    initial: (state, initialData) => {
      return {
        ...state,
        ...{
          [reduxManager.name]: {
            ...{
              [resultsPropName]: initialData,
              status: reduxManager.actionTypes.initial,
              error: null
            }
          }
        }
      };
    },
    success: (state, action) => {
      return {
        ...state,
        ...{
          [reduxManager.name]: {
            ...{
              [resultsPropName]: { ...state[reduxManager.name][resultsPropName], ...action.payload },
              status: reduxManager.actionTypes.success,
              error: null
            }
          }
        }
      };
    },
    inProgress: state => {
      return {
        ...state,
        ...{
          [reduxManager.name]: {
            ...state[reduxManager.name],
            ...{
              status: reduxManager.actionTypes.inProgress,
              error: null
            }
          }
        }
      };
    },
    failure: (state, action) => {
      return {
        ...state,
        ...{
          [reduxManager.name]: {
            ...state[reduxManager.name],
            ...{
              status: reduxManager.actionTypes.failure,
              error: action.payload
            }
          }
        }
      };
    }
  };
};

export { makeReducerMethods };

However if you require custom shape for your state you can pass your own in as a property to the createReduxManager method


const makeReducerMethods = (reduxManager, resultsPropName) => {
  return {
    success: (state, action) => {
      return {
        ...state,
        ...{
          [resultsPropName]: action.payload,
          [reduxManager.name]: {
            status: reduxManager.actionTypes.success,
            error: null
          }
        }
      };
    },
    inProgress: (state, action, initial) => {
      return {
        ...state,
        ...{
          [resultsPropName]: initial,
          [reduxManager.name]: {
            status: reduxManager.actionTypes.inProgress,
            error: null
          }
        }
      };
    },
    failure: (state, action, initial) => {
      return {
        ...state,
        ...{
          [resultsPropName]: initial,
          [reduxManager.name]: {
            status: reduxManager.actionTypes.failure,
            error: action.payload
          }
        }
      };
    }
  };
};


export const getContentReduxManager = createReduxManager({
  name: 'GET_CONTENT',
  reducerMethods: makeReducerMethods
});

You can also create a single action creator

import { makeActionCreator } from 'another-redux-manager';

const inProgress = makeActionCreator('GET_CONTENT_IN_PROGRESS', 'payload');