Coder Social home page Coder Social logo

georapbox / redux-call-api-middleware Goto Github PK

View Code? Open in Web Editor NEW
3.0 3.0 0.0 157 KB

Redux middleware to perform api calls reducing action creators boilerplate

License: MIT License

JavaScript 100.00%
redux middleware actioncreator action api

redux-call-api-middleware's Introduction

npm version Build Status Codecov Dependencies devDependency Status npm license

redux-call-api-middleware

Redux middleware to perform api calls reducing action creators boilerplate

This is a slight modification of the example found in Redux docs.

Install

$ npm install @georapbox/redux-call-api-middleware

Usage

After passing it once to applyMiddleware(...middlewares), you can write all your API-calling action creators the following way:

export function loadPosts(userId) {
  return {
    // Types of actions to emit before and after (required)
    types: {
      requestType: 'LOAD_POSTS_REQUEST',
      successType: 'LOAD_POSTS_SUCCESS',
      failureType: 'LOAD_POSTS_FAILURE'
    },

    // Check the cache (optional); defaults to `() => true`
    shouldCallAPI: state => !state.posts[userId],

    // Perform the fetching (required)
    callAPI: (dispatch, state) => fetch(`http://myapi.com/users/${userId}/posts`),

    // Arguments to inject in begin/end actions (optional); defaults to `{}`
    payload: { userId },

    // Callback function to be executed after `requestType` is dispatched (optional); defaults to `() => {}`
    onRequestDispatched: (payload, dispatch, state) => {
      // Do something when `requestType` is dispatched
    },

    // Callback function to be executed after `successType` is dispatched (optional); defaults to `() => {}`
    onSuccessDispatched: (response, payload, dispatch, state) => {
      // Do something when `successType` is dispatched
    },

    // Callback function to be executed after `failureType` is dispatched (optional); defaults to `() => {}`
    onFailureDispatched: (error, payload, dispatch, state) => {
      // Do something when `failureType` is dispatched
    }
  }
}

License

The MIT License (MIT)

redux-call-api-middleware's People

Contributors

georapbox avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

redux-call-api-middleware's Issues

When shouldCallAPI() returns false it should resolve instead of returning undefined (discussion)

// actions.js

export function loadPosts(userId) {
  return {
    types: {
      requestType: 'LOAD_POSTS_REQUEST',
      successType: 'LOAD_POSTS_SUCCESS',
      failureType: 'LOAD_POSTS_FAILURE'
    },
    shouldCallAPI: state => false,
    callAPI: (dispatch, state) => fetch(`http://myapi.com/users/${userId}/posts`),
    payload: { userId }
  }
}

// MyComponent.js

import React from 'react';
import { connect } from 'react-redux';
import { loadPosts } from './actions.js';

const MyComponent = props => {
  props.loadUserPosts('12345').then(res => {
    console.log(res);
  });
};

const mapDispatchToProps = dispatch => ({
  loadUserPosts: userId => dispatch(loadPosts(userId))
});

export default connect(null, mapDispatchToProps)(MyComponent);

In the example above, shouldCallAPI() returns false. Now when I call loadUserPosts and chain with a.then handler it will throw a TypeError because the middleware returns undefined. The conclusion is that when shouldCallAPI() is used and I need to chain I must always check if the returned result is undefined.

 const userPosts = props.loadUserPosts('12345');

if (userPosts) {
  userPosts.then(res => {
    console.log(res);
  });
}

Possible solutions:

  • The middleware could return Promise.resolve() when shouldCallAPI() is false instead of undefined. This way chaining would not lead to error.

Update dependecies

Update all dev dependencies and refactor build processes to comply with Babel 7.

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.