综合技术

Weird thing: Redux + Thunk + Axios + Typescript

微信扫一扫,分享到朋友圈

Weird thing: Redux + Thunk + Axios + Typescript
0

Redux and thunk are both weired things, but it’s not hard to squash them together using javascript, because in javascript you don’t have to worry about writing type-correct code

But in Typescript those creepy things are moved out from under the carpet. And you have to control them.

I spent hours to make it work. Here is the sample code.

To create a thunk action

// https://www.carlrippon.com/strongly-typed-react-redux-code-with-typescript/
export const fetchExampleAsyncAction: ActionCreator<
    //https://github.com/reduxjs/redux-thunk/blob/0e60b6264fb402afb328157c4337f5cc87a07b53/index.d.ts
    ThunkAction<
        Promise<Action>,  // The return type of the thunk's inner function
        Example,          // The redux state
        void,             // Optional extra argument passed to the inner function
        Action            // The (non-thunk) actions that can be dispatched.
    >> = () => {
    return async (dispatch: Dispatch) => {
        //the method body below returns an Action
        //With the "async" keyword for the function,  a Promise<Action> will be returned

        try {
            const response: AxiosResponse<Example> = await axios.get(BACKEND_URL_EXAMPLE);
            dispatch(new SetExampleAction(response.data));
            return handleFetchSuccess(dispatch);   //handleFetchSuccess() must return a non-thunk action
        } catch (error) {
            return handleFetchError(error, dispatch); //handleFetchError() must return a non-thunk action
        }
    };
};

To dispatch a thunk action

function mapDispatchToProps(dispatch: ThunkDispatch<any, any, AnyAction>) {
    return {
        fetchExample: () => dispatch(fetchExampleAsyncAction()),
        cleanExample: () => dispatch(cleanExampleLocallyAction())
    }
}

Note that I still used "any" in some places in the code, so my sample is not totally strong-typed. But I’ve tried my best.

阅读原文...


Avatar

Qualcomm’s Dean Brenner explains 5G spectrum and the ‘game-changer’ DSS

上一篇

Vue 2.x折腾记 - (22) Vue 打包图片在safari不显示的问题

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Weird thing: Redux + Thunk + Axios + Typescript

长按储存图像,分享给朋友