1.0.1 • Published 4 years ago

redux-simple-async v1.0.1

Weekly downloads
2
License
ISC
Repository
github
Last release
4 years ago

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))
});
1.0.1

4 years ago

1.0.0

4 years ago

0.0.1

4 years ago