0
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 Toolkitに入門してみた②

Last updated at Posted at 2021-06-24

この記事は
https://qiita.com/nisitin/items/ba91fb51885b0e98e4eb
の続編です!

Reduxの復習

Reduxは状態を管理するためのライブラリーです
大きく分けて三つの機能があります。

1.Action Creator(action)
2.store
3.reducer

上記の説明は①の記事に記載しているので省きますが、①の方を見るとさらに理解が深まると思います。

Redux ToolKitとReduxの比較

Reduxは必要最低限の機能しかなく、いくつもの部品を実装する必要があります。Reducer, state,switch文、ReducerのためのAction Creatorや、非同期通信を行いたかったらRedux Thunkなども必要になります。

Redux ToolkitではcreateSliceという関数があり既存のReduxでaction type定義とaction creatorを別々に定義していたものを一発で作られるようになりました。

Redux Toolkitの場合

※公式ドキュメントから抜粋

couterSlice.ts
import { createAsyncThunk, createSlice, payloadAction } from "@reduxjs/toolkit"

export interface CounterState {
  value: number;
  status: 'idle' | 'loading' | 'failed';
}


export initialState: CounterState = {
  value 0,
  status: "idle",
};

export const incrementAsync = createAsyncThunk(
  'counter/fetchCount',
  async (amount: number) => {
    const response = await fetchCount(amount);
    // The value we return becomes the `fulfilled` action payload
    return response.data;
  }
);  

const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    inclement: (state) => { 
        state.value += 1
    },
    decrement: (state) => {
        state.value -= 1; 
  },
)

このような感じでActionとReducerを定義できるようになり、Reduxよりも簡単に定義できるようになったと思います。
この中に出てくるcreateAsyncThunk関数は非同期処理の実行状況に応じたActionCreatorを生成する関数でReduxThunkが採用されています。そしてこのcreateAsyncThunkでは三つのActionを振り分けておりそれは

  • pending
  • fulfilled
  • rejected

になっています!

参考文献

https://zenn.dev/eitches/articles/2021-0329-redux-tool-kit
https://qiita.com/shikazuki/items/02fb27dc741cbff18811

0
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
0
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?