Skip to content

maymike321/redux-simple-async

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

redux-simple-async

Simple library for creating and firing off asynchronous actions in redux.

Install

npm install --save redux-simple-async

Adding as middleware

import { compose, applyMiddleware } from 'redux';
import { asyncMiddleware } from 'redux-simple-async'
...
const enhancers = [someMiddleware, someOtherMiddleware, asyncMiddleware, yetAnotherPieceOfMiddleware];
...
const store = createStore(rootReducer, compose(applyMiddleware(...enhancers)));

Usage

With no payload:

// getUsers.ts
export const getUsers = createAsyncAction('GET_USERS',
    async (dispatch, getState) => {
        try {
            const state = getState(); // use getState to get the state of the redux store
            const token = getToken(state);
            const users = await dispatch(getUsersFromApi(token)); // fire off and wait for other async actions
            dispatch(storeUsers(users));
        }
        catch (e) {
            dispatch(storeError(e));
        }
    }

// userPage.container.ts
const mapDispatchToProps = dispatch => ({
    loadUsers: () => dispatch(getUsers())
});

With Payload:

// editUser.ts
export const editUser = createAsyncAction<User>('EDIT_USER',
    async (dispatch, getState, userToEdit) => {
        try {
            const state = getState();
            const token = getToken(state);
            await dispatch(editUserFromApi(userToEdit, token));
        }
        catch (e) {
            dispatch(storeError(e));
        }
    });

//userPage.container.ts
const mapDispatchToProps = dispatch => ({
    editUser: (user) => dispatch(editUser(user))
});

About

Simple library for creating and firing off asynchronous actions in redux.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •