1.3.0 • Published 3 years ago

redux-response-middleware v1.3.0

Weekly downloads
12
License
ISC
Repository
github
Last release
3 years ago

Redux-Response-Middleware

Single Redux Middleware with Request/Success/Failure Pattern

Installation

npm i redux-response-middleware --save

Use

Add the middleware.

import { combineReducers, createStore, applyMiddleware } from 'redux';

import users from '@redux/users/reducer';
import posts from '@redux/posts/reducer';
import responseMiddleware from '@redux/helpers/responseMiddleware';

const reducers = combineReducers({ users, posts });

export default createStore(reducers, applyMiddleware(responseMiddleware()));

If the action has a service property you will receive corresponding props: data, error, loading, if these properties doesn't exist the action going to work as usually .

import { GET_POSTS, ADD_POST } from '@constants/actionNames';
import postServices from '@services/postServices';

const getPostsTarget = 'posts';
const addPostsTarget = 'post';

const success = (response) => {
  console.log('success:', response);
};

const failure = (error) => {
  console.log('error', error);
};

const postActions = {
  getPosts: (success, failure) => ({
    type: GET_POSTS,
    target: getPostsTarget,
    service: postServices.getPosts,
    response: resp => resp.data,
    error: error => error.data,
    success,
    failure,
  }),
  addPost: (values, success, failure) => ({
    type: ADD_POST,
    target: addPostsTarget,
    service: postServices.addPost(values),
    response: resp => resp.data,
    error: error => error.data,
    success,
    failure,
  }),
};

export default postActions;
OptionTypeDescription
typeStringYou should send a type name to handle from your reducer.
servicePromiseYou should send a promise, for example axios.get('posts').
targetStringThis is important to get good prop names, for example if target: 'post' you get props: postData, postError, postLoading.
initialState*The initial value ([], {}, '', etc)
responseFunc (optional)is a callback to handle the response route, for example if you have data: { data: { title } } you could use resp => resp.data.data, so that you can get in your redux state postData: { title } instead of postData: data: { data: { title } }.
errorFunc (options)Same as response option, but to handle errors.
successFunc (response)The callback when the response is success.
failureFunc (error)The callback when you get error
1.3.0

3 years ago

1.2.5

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.0.5

4 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

6 years ago

1.0.0

6 years ago