redux-thunk (非同期処理)

React

redux-thunkとは、Reduxで非同期処理をするための機能です

src/reducks/store/store.js

import thunk from 'redux-thunk';

export default function createStore(history) {
    return reduxCreateStore(
        combineReducers({
            -- --
        }),
        applyMiddleware(
            routeMiddleware(history),
            thunk  <--- 追加
        )
    );
}

src/reducks/users/operations.js

import { signInAction } from "./actions";

export const signIn = (email, password) => {
    return async (dispatch, getState) => {
        const state = getState()  <--- getState()で現在のstateの状態をGETします
        const isSignedIn = state.users.isSignedIn

        if (!isSignedIn) {
            const userData = await emailSignIn(email, password)  <--- asyncしてるのでawaitが使えます
            dispatch(signInAction({  <--- dispatchはactionをよびだすことができます
                isSignedIn: true,
                uid: "001",
                username: "jiro",
            }))
        }
    }
}

getStateは現在のstateの状態を呼び出せます

BACK