1.0.1 • Published 4 years ago

dymanic-reducer v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

Dynamic Reducer Generator

What does this libray does ?

Since, I am working with REST API for long time, I find my self writing a lot of reducer and making a lot of api call. For example, there might exist endpoint that simply fetch list of the data such /user/account, user/invoices, user/statements. For all these call, we need a reducer that store, fetch refresh the list of the invoice. For such request, we need to maintain multiple reducer, action and dispatcher and the code looks like dublicate and we might end up creating multiple files to store a reducer and actions consts.

This library attemps to generate a reducer, actions and dispatcher using JSON file store in constant folder and passing a function to combineReducer which will generate a reducer and required reducer. As well as the Action Constant are store as initial state in the reducer itself.

Methods expose by this library:

  • Generator
  • Request

What is Generator ?

Generator is the a function that will return a Reducer and Resource object if we supply a a following object as a argument.

It also take two other optional parameter. Optional parameter are discuss in later sections.

  {
    /**
      url is the endpoint from which you want to pull the date from backend.
    */
    url: "/todos",
    /*
     name of the reducer you want to generate. As per the name passed to the Generator function will assign a action name in the reducer.
     i.e.
     TODOS_SUCCESS
     TODOS_ERROR
     TODOS_UPDATE

    */
    name: "TODOS",
    /*
    if the url has query string you can pass it as a query string.
    */
    query: String

    /*
    If you just want to generate a Reducer but dont want to generate a reducer then you can set this flag as false. Which will only return a Resources.
    */
    hasReducer: Boolean

  }

Example Code:

// reducerConfig.js
const reducers = [
  {
    url: "/todo",
    name: "User",
    query: "",
    hasReducer: true
  }
];

const Reducers = Generator([...reducers], {}, {});

export default {
  // form: reduxFormReducer,  // uncomment for redux-form integration
  ...Reducers.filter(item => item.hasReducer).reduce((r, item) => {
    r = { ...r, [item.name]: item.reducer };
    return r;
  }, {})
};
// Object return by the Generator function.
[{
  name: "User"
  hasReducer: true
  reducer: Function,
}]

Here is the sample store configuration, we pass the reducer to the combine reducer.

// sample store config
/**
 * Creating store and and history.
 */
import storage from "redux-persist/lib/storage";
import { createStore, applyMiddleware } from "redux";
import { createLogger } from "redux-logger";
import promiseMiddleware from "redux-promise-middleware";
import { composeWithDevTools } from "redux-devtools-extension";
import { persistStore, persistCombineReducers } from "redux-persist";
import thunk from "redux-thunk";
import reducers from "../constant/reducerConfig";

const persistConfig = {
  key: "root",
  storage,
  whitelist: []
};
const middleware = [promiseMiddleware, thunk];

const persistedReducer = persistCombineReducers(persistConfig, reducers);

if (process.env.NODE_ENV === "development") {
  middleware.push(createLogger());
}

const store = createStore(
  persistedReducer,
  undefined,
  composeWithDevTools(
    applyMiddleware(...middleware)
    // other store enhancers if any
  )
);

const persistor = persistStore(store);

export { store, persistor };

Request :

Request is a function which will take a following object as argument and will return a a object of functions that can consume a object return by a Generator function.

If you pass a Resources to one of the function, it will make a api call and store a response to the reducer.

import { Request } from "dynamic-reducers";

const axiosConfig = {
  // if you want to set a header in globally for all the calls then you can pass a
  // header in the node below.
  header: {
    Accept: "application/json"
  },

  // intital node will take a Object which might contain following two keys.
  // apiHost is the API host end .
  // if you want it come from .env then it
  initial: {
    apiHost: "https://jsonplaceholder.typicode.com/", // process.env.REACT_APP_API_HOST
    contentType: "application/json" // to set a global content content type.
  },
  interceptors: false // Its a boolean field if you want to log the request to console.
};

// Passing the above object to Request methods which will return four function in a object.
const { GetRequest, PostRequest, PutRequest, DeleteRequest } = Request({
  ...axiosConfig
});

How to ? making a API Call and storing a response in Reducer and show in a UI ?

// this will show a sample api response methoods:

import React from "react";
import { connect } from "react-redux";
import { GetRequest } from "./constants/reducers";

class App extends React.Component {
 constructor(props) {
   super(props);
   const { Resources } = props.TODO;
   props.GetRequest({ ...Resources });
   this.state = {};
 }
 render() {
   const {
     TODO: { data = [] }
   } = this.props;
   return (
     <div className="App">
       <ui>
         {data.map(item => (
           <li>{item.title}</li>
         ))}
       </ui>
     </div>
   );
 }
}

function mapToState(state) {
 return {
   TODO: state.TODO
 };
}
1.0.1

4 years ago

1.0.0

4 years ago

0.0.19

4 years ago