1.0.4 • Published 6 years ago

redux-async-await-middleware v1.0.4

Weekly downloads
1
License
ISC
Repository
-
Last release
6 years ago

A middleware for Redux to handle side effects taking impurities from redux's actions and reducers.

Installation

To install the stable version:

npm install --save redux-async-await-middleware

This assumes you are using npm as your package manager.

const api = {
    getData: () => {
        return new Promise((resolve, reject) => {
            setTimeout(() => reject({ message: "Unable to fetch data" }), 2000);
        })
    }
}


//async function
export async function updateData(action, dispatch) {
    try{
    let data = await api.getData();
    dispatch({ type: 'SUCCESS_ACTION' , data })
    }
    catch(err){
         dispatch({ type: 'ERROR_ACTION' , data })
    }
  
}

//promise 

export function updateData(action, dispatch){
    api.getData()
    .then(data=>{
        dispatch({ type: 'SUCCESS_ACTION' , data })
    })
    .catch(err=>{
           dispatch({ type: 'ERROR_ACTION' , err })
    })
}

Suppose this is your async function where you will perform your async task (like api interaction).Async middleware will provide this function action and dispatch parameters.Here you will do your api interaction and dipatch success action.So all impurity will be captured here and reducer will be a pure function.

This is not only limited to async function. Promises can also be used with it to. Like in function below.

import { updateData } from './async-function';
import { asyncMiddleware } from 'redux-async-await-middleware';
import { applyMiddleware } from 'redux';

let middleware = asyncMiddleware({ UPDATE_DATA: updateData });

export const store = createStore(reducer, {}, applyMiddleware([middleware]));

Now you will import this function in other file and pass it to asyncMiddleware imported from this package and pass this in array of middlewares using applyMiddleware.And that's done.

Now it will listen to action UPDATE_DATA.And Fire corrosponding action.

Centeralized Error Handling

async Middleware also provide centeralized error handling.Pass the error handler function as second argument. Example below:

import { asyncMiddleware } from 'async-await-middleware';
import { applyMiddleware } from 'redux';



const ErrorHandler = (error, action, dispatch) => {

    switch (action.type) {
        case 'UPDATE_DATA':
            dispatch({ type: 'ERROR_ACTION', error });
    }

}


export async function updateData(action, dispatch) {
    let data = await api.getData();
    dispatch({ type: 'SUCCESS_ACTION' , data });
}


let middleware = asyncMiddleware({ UPDATE_DATA: updateData }, ErrorHandler);

export const store = createStore(reducer, {}, applyMiddleware([middleware]));

Now we don't have to do error handling in updateData. It will done in ErrorHandler function.