2.0.10 • Published 7 years ago
redux-api-middleware-native v2.0.10
Redux api middleware native
Api middleware for redux compatible with native and web apps.
Install
npm install --save redux-api-middleware-nativeAdding the middleware to redux store
import { createStore, applyMiddleware, combineReducers } from 'redux';
import apiMiddleware from 'redux-api-middleware-native';
import reducers from './reducers';
const reducer = combineReducers(reducers);
const initialState = {};
const store = createStore(reducer, initialState, applyMiddleware(
    apiMiddleware,
));Usage
import { CALL_API } from 'redux-api-middleware-native';
function action() {
    return {
        [CALL_API]: {
            endpoint: 'http://www.example.com/resource',
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: {
                'username' : 'npm-user',
                'password' : 'test'
            },
            types: ['SUCCESS', 'FAILURE', 'ERROR'],
            meta: {
                id: 'Data to reducer'
            }
        }
    }
}Custom payload / meta handler
import { CALL_API } from 'redux-api-middleware-native';
function action() {
    return {
        [CALL_API]: {
            endpoint: 'http://www.example.com/resource',
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: {
                'username' : 'npm-user',
                'password' : 'test'
            },
            types: [{
              type: 'SUCCESS',
              payload: (action, state, res) => {
                  return res.json().then((json) => {
                      // Inserting a header in response
                      json.token = res.headers.get('Authorization');
                      return json;
                  });
              },
              meta: (action, state) => {
                  return action.meta;
              }
            }, 'FAILURE', 'ERROR'],
            meta: {
                id: 'Data to reducer'
            }
        }
    }
}Responses
SUCCESS
Action {
    type = types[0]
    payload = JSON parsed response
    error = false
    meta = Any data that you sent
}FAILURE
Type failure means your request not get HTTP status code 200 without any other errors.
Action {
    type = types[1]
    payload = JSON parsed response
    error = true
    meta = Any data that you sent
}ERROR
Type error means we got exception on some point of code (ex. response parsing).
Action {
    type = types[2]
    payload = ERROR object
    error = true
    meta = Any data that you sent
}