• Stars
    star
    101
  • Rank 338,166 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

redux middleware that helps to manages async actions based on promise

redux-pender

Build Status npm version

Introduction

Redux pender is a middleware that helps you to manage asynchronous actions based on promise. It comes with useful tools that help you to handle this even more easier.

This library is inspired from redux-promise-middleware. The difference between redux-promise-middleware and this library is that this comes with some handy utils. Additionally, it also handles the cancellation of the promise-based action. To check out detailed comparisons between other libraries, please check Comparisons document

Installation

npm i --save redux-pender

Usage

Configure Store

import { applyMiddleware, createStore, combineReducers } from 'redux';
import penderMiddleware, { penderReducer } from 'redux-pender';

const reducers = {
    /*
        ...your other reducers...
    */
    pender: penderReducer
};

const store = createStore(
    reducers,
    applyMiddleware(penderMiddleware())
);

penderReducer is the reducer that tracks the status of your asynchronous actions.

  • When your request is pending, store.getState().pender.pending[ACTION_NAME] will turn true. It will set to false when it succeeds or fails.
  • When your request succeeds, store.getState().pender.success[ACTION_NAME] will turn true.
  • When your request fails, store.getState().pender.failure[ACTION_NAME] will turn true.

If you are currently using redux-promise or redux-promise-middleware in your project, there will be a collision. To avoid the collision without uninstalling existing library, pass { major: false } when you initialize the middleware:

penderMiddleware({ major: false })

Actions

pender middleware will process the action when a Promise is given as the payload of the action:

{
    type: 'ACTION_TYPE',
    payload: Promise.resolve()
}

If you have set major to false when you initialize the middleware to avoid the collision with redux-promise or redux-promise-middleware, the middleware will only accept following action:

{
    type: 'ACTION_TYPE',
    payload: {
        pend: Promise.resolve()
    }
}

By default, middleware will accept both of the kinds of actions above.

Dispatching actions

Since it supports FSA actions, you can use createAction of redux-actions. The second parameter of createAction should be a function that returns a Promise.

import axios from 'axios';
import { createAction } from 'redux-actions';

const loadPostApi = (postId) => axios.get(`https://jsonplaceholder.typicode.com/posts/${postId}`);
const LOAD_POST = 'LOAD_POST';
const loadPost = createAction(LOAD_POST, loadPostApi);
store.dispatch(loadPost(1));

If you are using this middleware as {major: false}, you have to use createPenderAction

import { createPenderAction } from 'redux-pender';
const loadPost = createPenderAction(LOAD_POST, loadPostApi);

It pretty much works quite the same, but it puts the Promise at action.payload.pend.

Reducer - handling actions

When you are making your reducer, it works the best when you are using handleActions of redux-actions. Handling action is done by using pender.

For people who don't know what handleActions does, it handles action by creating an object, rather than a switch.

import { handleActions } from 'redux-actions';
import { pender } from 'redux-pender';

const initialState = { 
    post: {}
}
export default handleActions({
    ...pender({
        type: LOAD_POST,
        onSuccess: (state, action) => {
            return {
                post: action.payload.data
            };
        }
    }),
    // ... other action handlers...
}, initialState);

Do you want to do something when the action starts or fails? It is simple.

...pender({
    type: LOAD_POST,
    onPending: (state, action) => {
        return state; // do something
    },
    onSuccess: (state, action) => {
        return {
            post: action.payload.data
        }
    },
    onFailure: (state, action) => {
        return state; // do something
    }
}, initialState)

When you omit one of those function, (state, action) => state will be the default value. Additionally, it is not recommended to manage the status of request in your own reducer, because the penderReducer will do this for you. You just need to care about the result of your task in your reducer.

applyPenders - helper function that allows you to apply penders super easily.

import { handleActions } from 'redux-actions';
import { pender, applyPenders } from 'redux-pender';

const initialState = { 
    post: {}
}

const reducer = handleActions({
    // ... some other action handlers...
}, initialState);

export default applyPenders(reducer, [
    {
        type: LOAD_POST,
        onPending: (state, action) => {
            return state; // do something
        },
        onSuccess: (state, action) => {
            return {
                post: action.payload.data
            }
        },
        onFailure: (state, action) => {
            return state; // do something
        }
    }
])

Cancellation

Cancelling the promise based action is very simple in redux-pender. You just have to call .cancel() from the returned value of your promise based action creator.

const p = loadPost(1);
p.cancel();

When cancel is executed, redux-pender middleware will dispatch ACTION_TYPE_CANCEL. You can handle that action manually or configure onCancel in the action pender.

...pender({
    type: LOAD_POST,
    onCancel: (state, action) => {
        return state; // do something
    }
}, initialState)

Using in your React Component

import React, { Component } from 'react';
import * as actions from './actions';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

class Example extends Component {

    componentDidMount() {
        this.fetchData();
    }

    async fetchData() {
        const { Actions } = this.props;
        try {
            await Actions.loadPost(1);
            console.log('data is fetched!');
        } catch(e) {
            console.log(e);
        }
    }

    render() {
        const { loading, post } = this.props;

        return (
            <div>
                { loading && 'Loading...' }
                <div>
                    <h1>{post.title}</h1>
                    <p>{post.body}</p>
                </div>
            </div>
        );
    }
}

export default connect(
    state => ({
        post: state.blog.post,
        loading: state.pender.pending['LOAD_POST']
    }),
    dispatch => ({
        Actions: bindActionCreators(actions, dispatch)
    })
)(Example)

Examples

An example project of using this library is provided in examples directory. If you want to see some more complex example, check out do-chat. It is a ChatApp project that uses firebase as backend.

Contributing

Contributions, questions and pull requests are all welcomed.

License

Copyright (c) 2017. Velopert Licensed with The MIT License (MIT)

More Repositories

1

velog

JavaScript
754
star
2

velog-client

TypeScript
679
star
3

learning-react

[๊ธธ๋ฒ—] ๋ฆฌ์•กํŠธ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ธฐ์ˆ  ์„œ์ ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ์ฝ”๋“œ
JavaScript
570
star
4

velog-server

TypeScript
362
star
5

react-tutorial

๋ฒจ๋กœํผํŠธ์™€ ํ•จ๊ป˜ํ•˜๋Š” ๋ชจ๋˜ ๋ฆฌ์•กํŠธ ํŠœํ† ๋ฆฌ์–ผ ๋ฌธ์„œ
JavaScript
348
star
6

velofolio

velofolio is yet another U.S. Stock backtest simulator tool. You can easily share your backtest or explore other's backtest within service. This service is currently in beta stage.
TypeScript
330
star
7

bitimulate

Simulated cryptocurrency trading system
JavaScript
262
star
8

sangte

Sangte is a fancy React state management library.
TypeScript
199
star
9

gin-rest-api-sample

Golang REST API sample with MariaDB integration using Gin and GORM
Go
189
star
10

ts-react-redux-tutorial

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ + ๋ฆฌ๋•์Šค๋ฅผ ํ”„๋กœ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•ด๋ด…์‹œ๋‹ค!
TypeScript
127
star
11

veltrends

Veltrends is a website website where users can explore trending tech news.
TypeScript
112
star
12

whotalk.us

Chat based SNS implemented using React.js on frontend-side and Node.js on backend-side - https://whotalk.us/
JavaScript
91
star
13

dealing-with-react-native

๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ธฐ์ˆ 
Java
88
star
14

learnjs

๋ฒจ๋กœํผํŠธ์™€ ํ•จ๊ป˜ํ•˜๋Š” ๋ชจ๋˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ
JavaScript
85
star
15

learn-react-testing

๋ฒจ๋กœํผํŠธ์™€ ํ•จ๊ป˜ํ•˜๋Š” ๋ฆฌ์•กํŠธ ํ…Œ์ŠคํŒ…
JavaScript
70
star
16

nodejs-jwt-example

sample implementation of an authentication system that uses JSON Web Token to manage users' login data in Node.js web server.
JavaScript
69
star
17

react-codelab-project

Single-page infinite-scrolling public memo app implemented using React.js, Redux, Express.js and MongoDB
JavaScript
58
star
18

react-webpack2-skeleton

Get started with React with Webpack2, React-Router, Redux, Code Splitting and Server Rendering
JavaScript
57
star
19

storybook-tutorial-code

Source code for storybook-tutorial
TypeScript
53
star
20

react-skeleton-2018

๋ฆฌ์•กํŠธ ํ”„๋กœ์ ํŠธ ์„ค์ •์„ 0๋ถ€ํ„ฐ ํ•ด๋ณด์ž.
JavaScript
50
star
21

react-tutorials

Sample projects from https://velopert.com/ (KOREAN)
JavaScript
43
star
22

develoxy

๊ฐœ๋ฐœ์ž๋“ค์˜ ๊ธ€์“ฐ๊ธฐ ํ”Œ๋žซํผ, develoxy
JavaScript
37
star
23

velo-ui

TypeScript
31
star
24

saysomething

Realtime Chat Application using long polling technique; implemented using Express.js, MongoDB and React.js
JavaScript
30
star
25

nodejs-github-webhook

Github Webhook server built with Node.js
JavaScript
29
star
26

react-codelab-fundamentals

Initial project used in React Codelab
JavaScript
29
star
27

typescript-react-sample

Sample project that uses Typescript, React, Redux, Immutable.js
TypeScript
24
star
28

mongoose_tutorial

RESTful API using MongoDB & Mongoose & Express
JavaScript
18
star
29

do-chat

Sample React ChatApp project that uses redux-pender
JavaScript
15
star
30

react-express-hmr-example

An example project of using React.js on Express.js server together with webpack-dev-server that has Hot Module Replacement enabled using react-hot-loader.
JavaScript
13
star
31

mooyaho-meet

Google Meet Clone implemented with Mooyaho
JavaScript
12
star
32

express-tutorial

express tutorial - covering ejs, resful api and session
JavaScript
12
star
33

react-ajax-tutorial

Ajax example in React
CSS
12
star
34

ArticlesApp

Sample App in ๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ธฐ์ˆ 
TypeScript
11
star
35

articles-server

๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ธฐ์ˆ ์˜ 15์žฅ React-Query์—์„œ ์‚ฌ์šฉํ•  Strapi๋กœ ๋งŒ๋“  ์ƒ˜ํ”Œ ๊ฒŒ์‹œ๊ธ€ ์„œ๋ฒ„
JavaScript
11
star
36

figma-icons-library-automation

JavaScript
9
star
37

gulp-es6-webpack

Use gulp to automatize ES6 transpilation in both client-side and server-side. (Express.js, babel, webpack, browser-sync, nodemon)
JavaScript
8
star
38

react-skeleton

React workspace that you can simply start coding right away
JavaScript
8
star
39

react-ssr-and-splitting

JavaScript
7
star
40

react-router-4-demo

Example project of using Pre-release version of React-Router v4. [Outdated]
JavaScript
7
star
41

learning-nodejs

JavaScript
6
star
42

react-query-ssr-react-router-sample

Sample Server Side Rendering project that uses React Router and React Query
JavaScript
6
star
43

typescript-nodejs-boilerplate

TypeScript / Node.js boilerplate with TSLint, Prettier enabled
JavaScript
6
star
44

velogthumb

On demand image resizing using Serverless / TypeScript
TypeScript
6
star
45

PublicGallery

JavaScript
5
star
46

react-codelab-memopad

JavaScript
4
star
47

react-memo-app

REST API ๊ธฐ๋ฐ˜ ๋ฆฌ์•กํŠธ ๋ฉ”๋ชจ ์•ฑ (๊ฐ•์˜์šฉ ํ”„๋กœ์ ํŠธ)
JavaScript
4
star
48

fc-seminar-react-todo

ํŒจ์ŠคํŠธ์บ ํผ์Šค ์ข‹์•˜์„๊ฑธ ์„ธ๋ฏธ๋‚˜ ๋ฆฌ์•กํŠธ ์ž…๋ฌธ ์„ธ์…˜์—์„œ ์‚ฌ์šฉ๋œ ํ”„๋กœ์ ํŠธ
JavaScript
3
star
49

react-remote-counter

An example project of using redux and express.js to demonstrate a simple counter that uses AJAX.
JavaScript
3
star
50

react-ssr-sample

React SSR Sample using redux, redux-thunk, react-router v4
JavaScript
3
star
51

DayLog

JavaScript
3
star
52

figma-svg-export-automation-sample

(WIP) Sample project that exports svg using Figma API
JavaScript
3
star
53

react-express-hot

React project generated using create-react-app; using with Express sever; react-hot-loader applied
JavaScript
1
star
54

react-sass-root-example

react-sass-root-example
JavaScript
1
star
55

react-router-tutorial

https://velopert.com/2937
JavaScript
1
star
56

react-contact-project

JavaScript
1
star
57

react-async-example

JavaScript
1
star
58

react-todo-list

CSS Module + Sass ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์Šคํƒ€์ผ๋ง๋œ ๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ๋กœ ์ด๋ค„์ง„ ์ผ์ •๊ด€๋ฆฌ ์˜ˆ์ œ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ž…๋‹ˆ๋‹ค
JavaScript
1
star