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

@sullivan/redux-config

v0.6.0

Published

Reduces redux boilerplate with a configurable structure

Downloads

132

Readme

Downloads Version License

redux-config

Reduces boilerplate for redux into a simple configuration pattern

Installation

yarn add @sullivan/redux-config
# or
npm i --save @sullivan/redux-config

Documentation

Example Usage

Constants

Let's start with the most common approach to creating a modularized redux architecture, constants. We know we want to fetch some posts and also have the ability to toggle visiblity.

import { constants } from '@sullivan/redux-config';

const { POST_FETCH, POST_TOGGLE } = constants([
  {
    invocation: 'async',
    namespace: 'post',
    verbs: ['fetch'],
  },
  {
    namespace: 'post',
    verbs: ['toggle'],
  },
]);

Since we are making an asynchronous call to get posts, so we will use the async invocation value to generate an enum for use later in our action and reducer.

Actions

Now we can make a couple action dispatchers that will use these constants. Keep in mind, our created action config will need to be initialized with the stores dispatch method.

import { actions } from '@sullivan/redux-config';

const { POST_FETCH, POST_TOGGLE } = // constants

const curriedActions = actions({
  fetchPosts: {
    type: POST_FETCH,
    invocation: 'async',
    fn: async () => [
      {
        id: '1',
        visible: true,
        comment: 'hello',
      },
      {
        id: '2',
        visible: true,
        comment: 'oh hi!',
      },
    ],
  },
  togglePostVisiblity: {
    type: POST_TOGGLE,
  },
});

The async invocation will handle specific states such as REQUESTED, SUCCEEDED, FAILED, and DONE automatically. Wheres the togglePostVisiblity will generate a function and dispatch our action type with whatever params are passed to it.

Reducer

Now we want our reducers to update states based on our actions that are dispatched. We want to cover the basic cases, like posts responding, loading states, and the visibility toggle.

import { reducers } from '@sullivan/redux-config';

const { POST_FETCH, POST_TOGGLE } = // constants

const reducer = reducers([
  {
    type: POST_FETCH.REQUESTED,
    path: 'posts.loading',
    fn: () => true,
  },
  {
    type: POST_FETCH.SUCCEEDED,
    path: 'posts.items',
    fn: (state, data) => data,
  },
  {
    type: POST_FETCH.DONE,
    path: 'posts.loading',
    fn: () => false,
  },

  {
    type: POST_TOGGLE,
    path: 'posts.items',
    fn: (state = [], { id }) =>
      state.map((it) => {
        if (id === it.id) {
          return {
            ...it,
            visible: !it.visible,
          };
        }
        return it;
      }),
  },
]);

Take note of the path used within the type configuration. When the reducer is ran, the state at that path will be used and passed to it. If the path doesn't exist it will be created for you. However, the initial value will not be set, so using a fallback initial value in the fn declaration is still suggests.

Putting it together

import { createStore, applyMiddleware } from 'redux';
import { constants, actions, reducers } from '@sullivan/redux-config';

const logger = (s) => (n) => (a) => {
  console.log('Action:', a);
  const response = n(a);

  console.log('State:', JSON.stringify(s.getState(), null, 2));
  return response;
};

const { POST_FETCH, POST_TOGGLE } = constants([
  {
    invocation: 'async',
    namespace: 'post',
    verbs: ['fetch'],
  },
  {
    namespace: 'post',
    verbs: ['toggle'],
  },
]);

const reducer = reducers([
  {
    type: POST_FETCH.REQUESTED,
    path: 'posts.loading',
    fn: () => true,
  },
  {
    type: POST_FETCH.SUCCEEDED,
    path: 'posts.items',
    fn: (state, data) => data,
  },
  {
    type: POST_FETCH.DONE,
    path: 'posts.loading',
    fn: () => false,
  },

  {
    type: POST_TOGGLE,
    path: 'posts.items',
    fn: (state = [], { id }) =>
      state.map((it) => {
        if (id === it.id) {
          return {
            ...it,
            visible: !it.visible,
          };
        }
        return it;
      }),
  },
]);

const curriedActions = actions({
  fetchPosts: {
    type: POST_FETCH,
    invocation: 'async',
    fn: async () => [
      {
        id: '1',
        visible: true,
        comment: 'hello',
      },
      {
        id: '2',
        visible: true,
        comment: 'oh hi!',
      },
    ],
  },
  togglePostVisiblity: {
    type: POST_TOGGLE,
  },
});

const store = createStore(reducer, {}, applyMiddleware(logger));

const createdActions = curriedActions(store.dispatch);

createdActions.fetchPosts().then(() => {
  createdActions.togglePostVisiblity({ id: '2' });
});

Output:

Action: { type: '@POST/FETCH_REQUESTED', payload: [] }
State: {
  "posts": {
    "loading": true
  }
}
Action: {
  type: '@POST/FETCH_SUCCEEDED',
  payload: [
    { id: '1', visible: true, comment: 'hello' },
    { id: '2', visible: true, comment: 'oh hi!' }
  ]
}
State: {
  "posts": {
    "loading": true,
    "items": [
      {
        "id": "1",
        "visible": true,
        "comment": "hello"
      },
      {
        "id": "2",
        "visible": true,
        "comment": "oh hi!"
      }
    ]
  }
}
Action: { type: '@POST/FETCH_DONE' }
State: {
  "posts": {
    "loading": false,
    "items": [
      {
        "id": "1",
        "visible": true,
        "comment": "hello"
      },
      {
        "id": "2",
        "visible": true,
        "comment": "oh hi!"
      }
    ]
  }
}
Action: { type: '@POST/TOGGLE', payload: { id: '2' } }
State: {
  "posts": {
    "loading": false,
    "items": [
      {
        "id": "1",
        "visible": true,
        "comment": "hello"
      },
      {
        "id": "2",
        "visible": false,
        "comment": "oh hi!"
      }
    ]
  }
}

Changelog

0.6.0

  • Updating how reducer config is declared
  • Deprecated invocationType in favor of invocation
  • Performance improvements

0.5.3

  • Expose the actionCreator for one-off actions