1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

redux-thunkで非同期処理を学んだ

Posted at

はじめに

・クエリを投げたり、APIを叩いて何かしら通信を発生する際に返ってきた実行結果やデータベースの中の情報を使って次の処理を進めたい
・Reduxだけではレスポンスを待つことができない。Reduxの中で非同期処理をしたい。(storeに保存)

こういった悩みを解決してくれるのがredux-thunkというライブラリです。
今回はこのライブラリについて学んだことを備忘録として書き留めます。

redux-thunkとは

Reduxで非同期処理を制御するライブラリ

通常のActionsはaction objectを受け取る = 関数を受け取ることはできない = async/awaitやpromiseを使えない
しかし、redux-thunkを使えばActionで非同期処理を管理することができる。

redux-thunkの導入方法

storeに対して導入します。
1.モジュールimport
2.applyMiddleware()に追加 *applyMiddlewareは導入したいMiddlewareの数だけ引数に取ることができる。

redux-thunkを用いた非同期処理の基礎文法

ここでは、仮にoperations.jsというファイルにredux-thunk使って非同期処理行います。
ファイルの役割 =>
1.複雑な処理を任せられる
2.redux-thunkで非同期処理を制御する
3.Actionsを呼び出す

operations.js
export const signIn = (email, password) => {
    return async (dispatch, getState) => {
     //現在のsigned inの状態を取得する
        const state = getState()
        const isSignedIn = state.users.isSignedIn
           
        if (!isSignedIn) {
              const userData = await emailSignIn(email, password)
              dispatch(signInAction({
                  isSignedIn: true,
                  uid: "00001",
                  username: "john",
              }))
         }
    }
}

getState() = 現在のstoreのstateを取得できる

そして、この後ログインを管理するファイルの中でこのoperations.jsをimportする。

login.js
<button onClick={() => dispatch(signIn())}>

参考

日本一わかりやすいReact-Redux入門#9...redux-thunkで非同期処理を制御すべし

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?