Code Monkey home page Code Monkey logo

redux-xhr-middleware's Introduction

redux-xhr-middleware Build Status

Async XHR middleware for Redux

A light-weight middleware for Redux to do promise-based XHR requests. XHR headers and API gateway uri are configurable.

Installation

yarn add redux-xhr-middleware

1. Plug into your Redux store

import {createStore, applyMiddleware} from 'redux';
import xhrMiddlewareCreator from 'redux-xhr-middleware';
import rootReducer from '../myRouteReducer';

const createReduxStore = initialState => {
  const xhrMiddleware = xhrMiddlewareCreator();
  let enhancer = applyMiddleware(xhrMiddleware);
  return createStore(
    rootReducer,
    initialState,
    enhancer
  );
};

const store = createReduxStore();

2. Use in your action creators to initiate XHR

Your action creator needs to return an object with types and xhr properties, both must be provided.

const GET_AUTHORS_REQUEST = 'GET_AUTHORS_REQUEST';
const GET_AUTHORS_SUCCESS = 'GET_AUTHORS_SUCCESS';
const GET_AUTHORS_FAIL = 'GET_AUTHORS_FAIL';

const getAuthors = (authorId = '') => {
  const url = siteId ? `/api/authors/${authorId}` : '/api/authors';
  return {
    types: [GET_AUTHORS_REQUEST, GET_AUTHORS_SUCCESS, GET_AUTHORS_FAIL],
    xhr: {
      url,
      method: 'GET'
    }
  };
};

3. Finally, handle your actions in reducer:

import merge from 'lodash/merge';

  // ...
  [GET_AUTHORS_REQUEST]: state => Object.assign({}, state, {
    fetchError: null,
    authors: [], // * see note below
    isGetting: true
  }),
  [GET_AUTHORS_SUCCESS]: (state, {payload}) => merge({}, state, {
    isGetting: false,
    authors: payload  // * see note below
  }),
  [GET_AUTHORS_FAIL]: (state, {payload}) => Object.assign({}, initialState, {
    getError: payload,
    isGetting: false
  }),
  // ...
  // * note: If you use normalizr, you will not need to store entity data in these reducers,
  // your dedicated 'entities' normalising reducer will keep that data.

Configuring XHR middleware

You can specify an options object to the XHR middleware creator:

const options = {
  apiHeaders: {},
  apiGateway: ''
};
const xhrMiddleware = xhrMiddlewareCreator(options);

apiHeaders can add/override any XHR header other than Accept and Content-Type headers, which are set as application/json by default.

apiGateway is a string as prefix to the paths, in case the API gateway is different to the application server, e.g. apiGateway could be https://myGateway.com:8081.

Example:

const options = {
  apiHeaders: {
    Authorization:  'my token'
  },
  apiGateway: '/api'
};

Customising header on a single XHR request

In your action creator, you can customise the HTTP header for your request.

const CREATE_AUTHORS_REQUEST = 'CREATE_AUTHORS_REQUEST';
const CREATE_AUTHORS_SUCCESS = 'CREATE_AUTHORS_SUCCESS';
const CREATE_AUTHORS_FAIL = 'CREATE_AUTHORS_FAIL';

const createAuthor = (payload) => {
  const url = '/api/authors';
  return {
    types: [CREATE_AUTHORS_REQUEST, CREATE_AUTHORS_SUCCESS, CREATE_AUTHORS_FAIL],
    xhr: {
      url,
      method: 'POST',
      headers: {
        'Accept': 'text/plain'
      },
      data: JSON.stringify(payload)
    }
  };
};

redux-xhr-middleware's People

Contributors

celikmus avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

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.