Giter Site home page Giter Site logo

hideaway's Introduction

Hideaway Middleware build status NPM

This middleware helps to standardize and reduce the code when you use stages (Request, Response, Error) or use redux with nested path.

Installation

npm install hideaway

or

yarn add hideaway

Why do I need this?

If you want to standardize the use redux and/or redux-thunk inside react with react-redux.

It is useful to work with calls to API and handling loading actions. (Require redux-thunk)

Work with nested path inside the reducer.

Examples

This is an interactive version of the code that you can play with online.

Settings

Store

Then, to enable hideaway, use applyMiddleware():

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { hideaway } from 'hideaway';

const middleware = [hideaway(), thunk];
createStore(reducers, applyMiddleware(...middleware));

Composition

Simple (without use of thunk)

action.js

export const incrementAction = () => ({
  type: 'INCREMENT',
});

export const decrementAction = () => ({
  type: 'DECREMENT',
});

reducer.js

import { combineReducers } from 'redux';
import { ReducerManagement } from 'hideaway';

const reducerManagement = new ReducerManagement({
  initialState: 0,
});

const counterReducers = reducerManagement.combine({
  INCREMENT: (state) => state + 1,
  DECREMENT: (state) => state - 1,
});

export const reducers = combineReducers({ counter: counterReducers });

selector.js

import { getValue } from 'hideaway';

export const getCounter = (state) => {
  return getValue(state, {
    path: ['counter'],
  });
};

API (use of redux-thunk)

action.js

import { generateAction } from 'hideaway';

export const getScore = () =>
  generateStateManagerAction('FETCH_SCORE', () => fetch('http://<HOST>'));

// ...

reducer.js

import { combineReducers } from 'redux';
import { ReducerManagement } from 'hideaway';

const reducerManagement = new ReducerManagement({
  initialState: 0,
  isStateManager: true,
});

const counterReducers = reducerManagement.combine({
  INCREMENT: (state) => state + 1,
  DECREMENT: (state) => state - 1,
});

export const reducers = combineReducers({ counter: counterReducers });

selector.js

import { getState } from 'hideaway';

export const getCounter = (state) => {
  return getState(state, {
    path: ['counter'],
  });
};

Combinations

Check the examples to see the variations.

Documentation

hideaway

The method enables to set the following settings:

parameter description
onError It calls when an error on API occurs. It receives the action with the response inside the payload.
withExtraArgument Inject a custom argument to be on API calls.
const onError = (action) => console.log(action);
const secret = 42;

const store = createStore(
  reducer,
  applyMiddleware(hideaway({ onError, withExtraArgument: { secret } }), thunk),
);

// later
export const fetchUser = (id) =>
  generateAction('FETCH_USER', (dispatch, getState, extraArg) => {
    // API call
  }));

generateAction

Format the action to be readable to the hideaway.

parameter description
type Property that indicates the type of action being performed
api Function that returns a promise. The function receive (dispatch, getState, extra) from the middleware.
options Additional settings (see the attributes below)

options

parameter description
apiPreReducer It receives the body after the api call and expect a result that will send to the reducer.
keys It is used to generate the nest path.
path It is used with keys to generate the nested path. If the keys match with an item inside the path, the value of the key will replace it.
allObject It returns the object instead the value from the nested path.
complement A complement for the action, to be used inside the reducer.
predicate Skip the fetch if predicate is false.
onError It calls when an error on API occurs. It receives the action with the response inside the payload.
isStateManager Define how to handle the api request. The default is false (It handles REQUEST, RESPONSE, ERROR).
export const fetchUser = (id) =>
  generateAction('FETCH_USER', (dispatch, getState, extraArg) => {
    // API call
  }, {
    // options here
  }));

generateStateManagerAction

Format the action to be readable to the hideaway and request to use the state manager feature.

parameter description
type Property that indicates the type of action being performed
api Function that returns a promise. The function receive (dispatch, getState, extra) from the middleware.
options Additional settings (see the attributes below)

options

parameter description
apiPreReducer It receives the body after the api call and expect a result that will send to the reducer.
keys It is used to generate the nest path.
path It is used with keys to generate the nested path. If the keys match with an item inside the path, the value of the key will replace it.
allObject It returns the object instead the value from the nested path.
complement A complement for the action, to be used inside the reducer.
predicate Skip the fetch if predicate is false.
onError It calls when an error on API occurs. It receives the action with the response inside the payload.
isStateManager Define how to handle the api request. The default is true (It handles REQUEST, RESPONSE, ERROR).
export const fetchUser = (id) =>
  generateStateManagerAction('FETCH_USER', (dispatch, getState, extraArg) => {
    // API call
  }, {
    // options here
  }));

ReducerManagement

parameter description
initialState Sset an initial state for the reducer. For nested that doesn't set the nested, it will assing to a root key
displayError It display the error on console if the fetch fails.
isNested It enables nested path. (Default: false)
nested Settings necessary if it sets isNested. (*)
isStateManager It enables the state manager for API use. (default: false)

(*) The setting will use with initialState for the fist time only.

nested

parameter description
keys It is used to generate the nest path.
path It is used with keys to generate the nested path. If the keys match with an item inside the path, the value of the key will replace it.

ReducerStateManagement

parameter description
initialState Sset an initial state for the reducer. For nested that doesn't set the nested, it will assing to a root key
displayError It display the error on console if the fetch fails.
isNested It enables nested path. (Default: false)
nested Settings necessary if it sets isNested. (*)
isStateManager It enables the state manager for API use. (default: true)

(*) The setting will use with initialState for the fist time only.

nested

parameter description
keys It is used to generate the nest path.
path It is used with keys to generate the nested path. If the keys match with an item inside the path, the value of the key will replace it.

getValue

Retrieve the value from state

parameter description
state The state container
options Additional settings (see the attributes below)

options

parameter description
path It is used to find the initial path. (nested path is the complement)
defaultValue Value to return if doesn't find the path or the value is null. (default: null)
nested See nested.
isStateManager Inform to return the loading, value and error when the result is empty or null. (default: false)

getState

Retrieve the value from state using the state manager format

parameter description
state The state container
options Additional settings (see the attributes below)

options

parameter description
path It is used to find the initial path. (nested path is the complement)
defaultValue Value to return if doesn't find the path or the value is null. (default: null)
nested See nested.
isStateManager Inform to return the loading, value and error when the result is empty or null. (default: true)

hideaway's People

Contributors

ozahata avatar

Watchers

 avatar

Forkers

cinemaster

hideaway's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.