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

redux-api-struct

v0.2.0

Published

![ReduxAPIStruct Logo](https://raw.githubusercontent.com/konojunya/redux-api-struct/master/logo/logo.png)

Downloads

7

Readme

ReduxAPIStruct Logo

npm CircleCI MIT License

redux-api-struct makes it easy to manage the state of the API for redux's state.

Description

redux-api-struct provides types and utils for store.

By managing the state with initial fetching, success and failure, it is possible to easily switch the UI on the component side, making the error report easier to write due to the structure of the error, or letting the error sentence depend on the action.

Installation

install with npm or yarn

  • npm
npm install --save redux-api-struct
  • yarn
yarn add redux-api-struct

Usage

redux-api-struct is supposed to be used with redux.

sample is an example using typescript-fsa and typescript-fsa-reducers.

import { reducerWithInitialState } from "typescript-fsa-reducers";
import {
  ReduxAPIStruct,
  ReduxAPIState,
  createDefaultStruct
} from "redux-api-struct";

/**
 * To createDefaultStruct, pass in the generic type such as API response,
 * give the default value. If there is no default value,
 * undefined is substituted.
 */
export interface InitialState {
  user: ReduxAPIStrcut<number>
}

// case no defualt value
export const initialState: InitialState = {
  count: createDefaultStruct<number>()
}

// case default value is 0
export const initialState: InitialState = {
  count: createDefaultStruct<number>(0)
}

// reducer
export const sampleReducer = reducerWithInitialState(initialState)
  .case(ActionCreator.request, state => {
    ...state,
    count: {
      ...state.count,
      state: ReduxAPIState.FETCHING
    }
  })
  .case(ActionCreator.success, (state, payload) => {
    ...state,
    count: {
       ...state.count,
       state: ReduxAPIState.SUCCESS,
       data: payload
    }
  })
  .case(ActionCreator.failure, (state, error) => {
    ...state,
    count: {
      ...state.count,
      state: ReduxAPIState.FAILURE,
      error
    }
  })

actionCreator.ts

import actionCreatorFactory from "typescript-fsa";
import { ReduxAPIError } from "redux-api-struct";

const actionCreator = actionCreatorFactory("sample");

// actionCreator
export type RequestPayload = void;
export const request = actionCreator<RequestPayload>("REQUEST");

export type SuccessPayload = number;
export const success = actionCreator<SuccessPayload>("SUCCESS");

export type FailurePayload = ReduxAPIError;
export const failure = actionCreator<FailurePayload>("FAILURE");

export const nextCount = () => async (dispatch, getState) => {
  const { sampleReducer } = getState();
  dispatch(request());

  let num: number = sampleReducer.count.data;
  try {
    const nextCount = await new Promise<number>((resolve, reject) => {
      setTimeout(() => {
        if (Math.floor(Math.random() * 4) === 0) {
          reject(new Error("request failure"));
        }
        resolve(++num);
      }, 500);
    });
    dispatch(success(nextCount));
  } catch (error) {
    // Depending on the type of ReduxAPIError, statusCode, error and message are required.
    dispatch(
      failure({
        statusCode: 500,
        error
      })
    );
  }
};

in component

import * as React from "react";
import { connect } from "react-redux";
import { ReduxAPIStruct, ReduxAPIState } from "redux-api-struct";
import { nextCount } from "./action"

interface Props {
  count: ReduxAPIStruct<number>;
  nextCount: typeof nextCount;
}

const Component: React.FunctionComponent<Props> = ({ count, nextCount }) => {
  const countComponent = (() => {
    switch(count) {
      case ReduxAPIState.INITIAL:
      case ReduxAPIState.FETCHING:
        return <p>loading...</p>
      case ReduxAPIState.SUCCESS:
        return <p>{count.data}</p>
      caes ReduxAPIState.FAILURE:
        return <p>failure component</p>
    }
  })()

  <>
    {countComponent}
    <button onClick={nextCount}>+1</button>
  </>
}

const Counter = connect(
  state => ({
    count: state.sampleReducer.count
  }),
  dispatch => ({
    nextCount: () => dispatch(nextCount())
  })
)(Component)

export { Counter }

API

The state wrapped by ReduxAPIStruct has the following state.

  • status
  • data
  • error

status: ReduxAPIState

status is for describing the situation with the API with the following enums briefly. Components can use this enum to separate out depending on the state.

enum ReduxAPIState {
  INITIAL,
  FETCHING,
  SUCCESS,
  FAILURE
}

data: T

data is given the type of generics given by the type of ReduxAPIStruct.

The actual response returned by the API will be included in this data.

error: ReduxAPIError

error requires three states. Only the statusCode is mandatory. The error type of the component is switched by statusCode so that error main body is put on because it is used for error reporting. message makes it easy to issue arbitrary error statements to action.

createDefaultStruct: (default?: any) => ReduxAPIStruct

In createDefaultStruct, it is possible to give the default value as optional. You can get the benefit of ReduxAPIStruct by setting the return value of this method to the state of reducer.

errorDefault: () => ReduxAPIError

errorDefault is a method to initially generate a state for managing errors. Use it to generate a test code or an arbitrary error.

Logo

created by kinokoruumu

you can see logo dir

License

MIT