question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add separate project for async-thunk implementation

See original GitHub issue

@aikoven provided a solution for redux-thunk integration and I think this should be a separate package with the util + documentation. I use redux-thunk, so I can contribute to the usage documentation.

I have modified it slightly for readability and added TError generic.

import { AsyncActionCreators } from 'typescript-fsa'

// https://github.com/aikoven/typescript-fsa/issues/5#issuecomment-255347353
function wrapAsyncWorker<TParameters, TSuccess, TError>(
  asyncAction: AsyncActionCreators<TParameters, TSuccess, TError>,
  worker: (params: TParameters) => Promise<TSuccess>,
) {
  return function wrappedWorker(dispatch, params: TParameters): Promise<TSuccess> {
    dispatch(asyncAction.started(params));
    return worker(params).then(result => {
      dispatch(asyncAction.done({ params, result }));
      return result;
    }, (error: TError) => {
      dispatch(asyncAction.failed({ params, error }));
      throw error;
    });
  }
}

export default wrapAsyncWorker

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
xdavecommented, Jun 1, 2017

I was thinking about making wrapAsyncWorker act like how I declare thunks already, so I wrote this:

import { Dispatch } from "redux";
import { ThunkAction } from "redux-thunk";
import { AsyncActionCreators } from "typescript-fsa/lib";

type Thunk<R> = ThunkAction<Promise<R>, any, any>;

type AsyncWorker<R, P, S = any, T = any> =
    (params: P, dispatch: Dispatch<S>, getState: () => S, extra: T) => Promise<R>;

export const createThunk = <P, R, E>(
    actions: AsyncActionCreators<P, R, E>,
    worker: AsyncWorker<R, P>
) => (params: P): Thunk<R> => async (dispatch, getState, extra) => {
    dispatch(actions.started(params));
    try {
        const result = await worker(params, dispatch, getState, extra);
        dispatch(actions.done({ params, result }));
        return result;
    } catch (error) {
        dispatch(actions.failed({ params, error }));
        throw error;
    }
};

You use it like this (for example):

import actionCreatorFactory from 'typescript-fsa';
import { createThunk } from "../util/async";
import { App } from "../types";

const create = actionCreatorFactory('posts');

export const getPostActions = create.async<
    App.Post.GetParams,
    App.Post.Result,
    App.Post.Failure>('GET');

export const getPost = createThunk(getPostActions, async params => {
    const url = `https://jsonplaceholder.typicode.com/posts/${params.id}`;
    const response = await fetch(url);
    if (response.status >= 400) {
        throw new Error(`Server Error: ${response.status}`);
    }
    return response.json() as Promise<App.Post.Result>;
});

And then somewhere later:

import { getPost } from '../actions/posts';

...

    dispatch(getPost({ id: 1 }));

....
3reactions
xdavecommented, Jun 17, 2017

@ttamminen @aikoven https://github.com/xdave/typescript-fsa-redux-thunk

npm install --save typescript-fsa-redux-thunk or yarn add typescript-fsa-redux-thunk

Read more comments on GitHub >

github_iconTop Results From Across the Web

Setup a Redux Application using createAsyncThunk and React
Now let's set it up from scratch. Step 1: create a react project via the following: npx create-react-app reduxtoolkitapp. Step 2: Afterward, ...
Read more >
createAsyncThunk - Redux Toolkit
First, create the thunk const fetchUserById = createAsyncThunk( 'users/fetchByIdStatus', async (userId: number, thunkAPI) => {
Read more >
Using Redux Toolkit's createAsyncThunk - LogRocket Blog
Learn how to use the createAsyncThunk API to perform asynchronous tasks in Redux apps and handle common errors.
Read more >
Redux Toolkit Tutorial - 24 - Async Thunks - YouTube
Courses - https://learn.codevolution.dev/ Support UPI - https://support.codevolution.dev/ Support Paypal ...
Read more >
10#. How to use createAsyncThunk in redux toolkit - YouTube
React.js Real-World Projects. Lama Dev. Lama Dev ... NestJs Course for Beginners - Create a REST API. freeCodeCamp.org. freeCodeCamp.org.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found