1.0.3 • Published 6 years ago

redux-api-fetch-middleware v1.0.3

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

redux-api-fetch-middleware Build Status

Redux middleware to perform HTTP request with fetch

UNMAINTAINED PROJECT

I haven't updated this project in a while and also haven't used it so I'm setting this to be unmaintained!

Installation

npm install --save redux-api-fetch-middleware

This middleware makes use of the Fetch API. Check caniuse.com if the browsers you have to support have the Fetch API. If they don't you have to include a polyfill by yourself, e.g. isomorphic-fetch or the Github fetch polyfill. The fetchMiddleware expects a JSON response. Any other response formats will result in an error.

Usage

First you have to register redux-api-fetch-middleware as a middleware to redux:

import { createStore } from 'redux';
import fetchMiddleware from 'redux-api-fetch-middleware';

import reducer from './your-reducers';

let store = createStore(reducer, ['Initial State'], fetchMiddleware);

After registering you can use it anywhere when dispatching an action:

import { FETCH } from 'redux-api-fetch-middleware';

dispatch({
  type: FETCH,
  payload: {
    types: ["REQUEST", "SUCCESS", "FAIL"],
    endpoint: '/your/api/endpoint'
  }
});

Additionally you can pass the following in the action object:

  • meta: An object containing meta data. This information isn't processed by the fetchMiddleware but instead it is passed through when dispatching any of the 3 action types.

And the following is for the payload object:

  • method: The HTTP method to use. Defaults to "GET". When using a method like "POST" you might want to pass data in the body property.
  • body: An object containing data to be sent to the server.

The fetchMiddleware has the header credentials set by default with a value of same-origin which means it is sending cookies and session data to the server.

Format of triggered actions

The fetchMiddleware dispatches the 3 actions passed in payload.types:

  • REQUEST: This action is dispatched before the request is started. The action object looks like this: { type: payload.types[0] }.
  • SUCCESS: When the HTTP request was successful. The action object looks like this: { type: payload.types[1], payload: result, meta: meta }.
  • FAIL: When the HTTP request failed. Format of the action object: { type: payload.types[2], payload: { message: error }, error: true, meta: meta }

Copyright (c) 2016 Sammy Braun, licensed under MIT (see LICENSE)