simple-api-call-life-cycle

make api call with redux

Usage no npm install needed!

<script type="module">
  import simpleApiCallLifeCycle from 'https://cdn.skypack.dev/simple-api-call-life-cycle';
</script>

README

simple-api-call-life-cycle

NPM version

Install

$ npm install simple-api-call-life-cycle --save

Usage

$ A api call lifecycle library for redux combined with redux thunk to be reused for the entire project,
from action to reducer.

action.

import { ApiCall } from 'simple-api-call-life-cycle';
// Passing the type and define the action.
const FETCH_PRODUCTS = 'FETCH_PRODUCTS';
const fetchProductsAction = new ApiCall(FETCH_PRODUCTS);
const fetchProductsRequest = axios.get('url');

export const fetchProducts = fetchProductsAction.fetch.bind(
  fetchProductsAction,
  fetchProductsRequest
);
export { fetchProductsAction };

reducer.

import { fetchProductsAction } from '../actions';

const INITIAL_STATE = {
  isInProgress: undefined,
  isCompleted: undefined,
  hasFailed: undefined,
  products: []
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case fetchProductsAction.init:
    // set loading to be true.
    case fetchProductsAction.success:
    // Promise resolved
    case fetchProductsAction.fail:
    //
    default:
      return state;
  }
};

components.

if(!state.isCompleted) {
  fetchProducts();
}
if(this.props.state.isInProgress && !nextProps.state.isCompleted) {
  fetchProducts()
}
if(!state.isCompleted || state.isInProgress) {
  return <loader />
}