Git Product home page Git Product logo

redux-async's Introduction

redux-async

Build Status - Travis CI Test Coverage - Code Climate MIT NPM

Default reducer with reset functionality for Redux Toolkit's createAsyncThunk

Install

npm i @weavedev/redux-async

API documentation

We generate API documentation with TypeDoc.

API Documentation

Creating

In this example we create a reducer from a thunk. The async function inside the thunk will trigger its callback after 3 seconds.

import { createAsyncThunk } from '@reduxjs/toolkit';
import { createAsyncReducer } from '@weavedev/redux-async';

// First, create the thunk with @reduxjs/toolkit's createAsyncThunk
//     Docs, see: https://redux-toolkit.js.org/api/createAsyncThunk
export const runSayHello = createAsyncThunk(
    'say/hello',
    async (name: string): Promise<string> => {
        // This promise waits 3 seconds and then returns
        return new Promise((resolve: ((value: string) => void)): void => {
            setTimeout(() => {
                resolve(`Hey, ${name}!`);
            }, 3000);
        });
    },
);

// Then create the reducer from the thunk
export const sayHello = createAsyncReducer(runSayHello);

Triggering

You can run your async function by dispatching the thunk. If your Promise expects a parameter, you can pass it to the thunk.

import { runSayHello } from './runSayHello';
import { store } from './store';

// Dispatch the thunk on your store
store.dispatch(runSayHello('Dave'));

For more information, see Redux Toolkit: createAsyncThunk - Overview.

Resetting

If you pass an action as the second argument to createAsyncReducer the generated reducer will reset itself to its initial state when this action is dispatched.

If this is done while the thunk is 'pending', the corresponding 'rejected' or 'fulfilled' will be ignored (the thunk will still fire the action, but the state will not update).

import { createAction, createAsyncThunk } from '@reduxjs/toolkit';
import { createAsyncReducer } from '@weavedev/redux-async';

// First, create the thunk with @reduxjs/toolkit's createAsyncThunk
//     Docs, see: https://redux-toolkit.js.org/api/createAsyncThunk
export const runSayHello = createAsyncThunk(
    'say/hello',
    async (name: string): Promise<string> => {
        // This promise waits 3 seconds and then returns
        return new Promise((resolve: ((value: string) => void)): void => {
            setTimeout(() => {
                resolve(`Hey, ${name}!`);
            }, 3000);
        });
    },
);

// Create a reset action
//     We suggest adding `/reset` or `/initial` after your thunk action string
export const resetSayHello = createAction('say/hello/reset');

// Then create the reducer from the thunk and the reset action
export const sayHello = createAsyncReducer(runSayHello, resetSayHello);

To reset the state on your reducer, simply dispatch the reset action

store.dispatch(resetSayHello());

State

The state output contains the following fields

error?: any

The reducer will contain the rejected or thrown value in the error field if the Promise has rejected / thrown. This value will be cleared if you dispatch the thunk again (or on reset).

result?: ThunkResult

The reducer will contain the returned value in the result field if the Promise has resolved. This value will be cleared if you dispatch the thunk again (or on reset).

meta

The meta field contains a copy of the data in the meta field in Thunk's Promise Lifecycle Actions.

For example; when pending the meta field contains the following values:

requestId: string;
arg: ThunkArg;

The meta field also contains the requestStatus with the current state of the thunk.

requestStatus: 'initial' | 'pending' | 'fulfilled' | 'rejected';

meta.requestStatus: 'initial'

This is the requestStatus in the reducer, or the state after the reset action has been dispatched.

meta.requestStatus: 'pending'

This is the requestStatus in reducer while we are waiting for the Promise to resolve (or throw).

You can implement a busy indicator by checking meta.requestStatus === 'pending'.

meta.requestStatus: 'fulfilled'

This is the requestStatus in the reducer after the Promise has resolved. The reducer will also contain the returned value in the result field.

meta.requestStatus: 'rejected'

This is the requestStatus in the reducer after the Promise has rejected / thrown. The reducer will also contain the rejected or thrown value in the error field.

License

MIT

Made by Paul Gerarts and Weave

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.