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

@brendanatme/make-redux-state

v1.0.4

Published

Take the boilerplate out of redux.

Downloads

4

Readme

Make Redux State

Take the boilerplate out of redux.

Creates a slice of Redux state, and provides out-of-the-box reducers, actions for updating data and network status, and higher-order components

Store all your relevant state data in one object and cut out boilerplate without losing any flexibility in Redux.

Usage

Creating State

import { makeActionTypes, makeReduxState } from '@brendanatme/make-redux-state';
import { myApi } from './path/to/my-api';

const STATE_KEY = 'myStateSlice';

const ActionTypes = makeActionsTypes(STATE_KEY);

const options = {
  actions: {
    myCustomFetch: (...myActionArgs) => (dipatch, getState) => {
      dispatch({ type: ActionTypes.clear });
      
      myApi
        .fetchData(...myActionArgs)
        .then((data) => {
          dispatch({
            type: ActionTypes.onLoadSucceeded,
            payload: { data },
          });
        })
        .catch((error) => {
          dispatch({ type: ActionTypes.onLoadFailed });
        });
    },
  },
  initialState: { // with default shape
    currentId: '',
    data: {},
    failed: false,
    items: [],
    loaded: false,
  },
};

export const myState = makeReduxState(STATE_KEY, options);

Adding State to Redux

import { createStore, combineReducers } from 'redux';
import { myState } from './path/to/my-state';

const initialState = {
  [myState.key]: myState.initialState,
};

const reducer = combineReducers({
  [myState.key]: myState.reducer,
});

const myStore = createStore(reducer, initialState);

Injecting State Props into Components

You can use the "withProps" HOC method to inject your state props into a component.

import React from 'react';
import { myState } from './path/to/my-state';

const MyComponent = ({
  myStateSlice, // myState.key
}) => (
  <div>
    {myStateSlice.loaded ? (
      <span>{JSON.stringify(myStateSlice.data)}</span>
    ) : (
      <span>Loading...</span>
    )}
  </div>
);

export default myState.withProps(MyComponent);

Giving Containers access to State Actions

import React from 'react';
import MyComponent from './path/to/my-component';
import { myState } from './path/to/my-state';

class MyContainer extends React.Component {
  componentDidMount() {
    const args = {};
    this.props.myCustomFetch('any', args, 'you', 'want');
  }

  render() {
    return (
      <MyComponent />
    );
  }
}

export default myState.withActions(MyContainer);

API

makeActionTypes

@param {string} key the key of the piece of state you are creating @returns {Object} a hash of action type strings

Action Types:

  • clear: resets state slice to default state
  • onLoadFailed: sets "failed" flag to true
  • onLoadSucceeded: sets "failed" flag to false, "loaded" flag to true, and updates state with payload
  • setCurrentItem: sets the "currentId" property. Gives you access to a computed property "current" when you have items in the "items" array
  • update: updates state with payload. Useful catchall to perform any manual update you want in a custom action creator

Example:

const ActionTypes = makeActionTypes('users');

makeReduxState

@param {string} key the key of the piece of state you are creating @param {Object} options object containing custom action and custom initialState

Options:

{
  actions?: {
    [k: string]: (args: any) => (dispatch: function, getState: function) => void;
  };
  initialState?: {
    currentId: string;
    data: any;
    failed: boolean;
    items: [
      { id: string|number; ...any }
    ],
    loaded: boolean;
  };
}
  • Options.actions: a hash map of Redux action creators
  • Options.initialState: the custom initial state of your state slice

Example:

const ActionTypes = makeActionTypes('users');
const stateSlice = makeReduxState('users', {
  actions: {
    fetchUser: (id) => (dispatch, getState) => {
      // ... get user ...
      dispatch({
        type: ActionTypes.onLoadSucceeded,
        payload: {
          data: user,
        },
      });
    },
    doSomethingSpecial:
  },
  initialState: {
    data: {
      something: 'custom',
    },
  },
});

Returns: a ReduxState object with the following properties:

{
  actions: Object<{ [k: string]: Function }>
  initialState: Object;
  key: String;
  reducer: Function;
  withProps: Function;
  withActions: Function;
  withAll: Function;
}