LoginSignup
2
2

More than 1 year has passed since last update.

Reduxを使った認証処理の実装

Last updated at Posted at 2022-10-10

今回は、Reduxを利用して、login画面と、認証通過後のhome画面の実装を行っていきます。
今回は、reduxプロジェクトを新規で作成し、実装していきます。

それぞれのバージョンは以下

パッケージ名 インストールバージョン 機能
react-redux 8.0.2 状態管理ツール
react-router-dom 6.3.0 ルーティング機能
axios 1.1.2

実装

1.Reduxのプロジェクト作成

先ずは、以下のコマンドを実行し、reduxのプロジェクトを作成します。

$  npx create-react-app reduxtest --templete redux-typescript

最後に「Happy hacking!」と表示されていれば、正常にプロジェクトが作成されたことになります。

2.interfaceの実装

先ずは、前準備として、interfaceの実装を行います。

authTypes.ts
/* ログインする際のユーザ名とPWを格納するためのデータ型 */
export interface LOGIN_CREDENTIAL{
    username: string;
    password: string;
}

2.Sliceの実装

次に、Sliceを実装していきます。
Sliceには、大きく分けてActionとReducerという2つの処理を実装していきます。概要は以下。

処理名 概要
Acion 呼び出された際、どういう振る舞いをするか記載
Reducer 実装されているActionの結果の処理内容を記載

①Authenticationフォルダ内に、「authSlice.tsx」ファイルを作成します。
image.png

②Actionの実装
先ずは、Sliceの中に、Actionを記載していきます。
Actionは、呼び出されされた際の振る舞いをどうするか?を記載します。
今回は、「fetchAsyncLogin」が呼び出されたら、「LOGIN_CREDENTIAL」に格納されているされている値をURLへ送るという処理を行っています。

authSlice.ts
/* 認証のための非同期関数(Action) */
export const fetchAsyncLogin = createAsyncThunk(
    "auth/authentication",
    async (auth: LOGIN_CREDENTIAL) => {
        const res = await axios.post<Boolean>(
            /* サーバサイドのAPIを呼び出すためのURL */
            `http://127.0.0.1:8000/api/auth/authentication`,
            /* サーバサイドのAPIに渡す値を格納した引数 */
            auth,
            {
                /* APIを呼び出す際のヘッダ情報を記載 */
                headers: {
                    "Content-Type": "application/json"
                },
            }
        );
        return res.data;
    }
);

③Reducerの実装
Reducerは、②で実装したActionを実行した結果、どういった振る舞いを行うか?を記載しています。
今回は、②で実装した、「サーバサイドへ処理の依頼を行う」の結果、「/home」のURLへアクセスする処理の実装となります。

authSlice.ts
export const authSlice = createSlice({
    /* Reducer名 */
    name: "auth",
    initialState: false,
    reducers: {},
    extraReducers: (builder) => {
        /* fetchAsyncLoginが成功した場合の処理 */
        builder.addCase(
            fetchAsyncLogin.fulfilled,
            () => {
                /* /homeのリンクにアクセスする。 */
                window.location.href = "/home";
            }
        )
    }
});

④Reducerの登録
Reducerを実装したら、Storeが実装したReducerを利用できるようにする必要があります。
ここでは、Storeに、実装したReducerを登録します。

store.ts
export const store = configureStore({
  reducer: {
    /* authSlice内で実装したReducerをstoreで利用可能にする。 */
    auth: authReducer,
  },
});

⑤Home.tsxの実装
一応、簡単な遷移先のhome画面も作成しておきます。
ただのHomeと表示させるだけの簡単な内容となります。

Home.tsx
function Home() {
    return (
        <div>
            <h4>Home</h4>
        </div>
    )
}

export {Home}

動作検証

①ログイン画面に、ユーザIDとパスワードを入力してみます。
image.png

②サインインボタンをクリックしてみます。
Home画面に移行したことが確認できました。
image.png

今回作成した全コードは、以下のURLへ上げておきます。
https://github.com/NoriStock1983/redux_auth

以上

2
2
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
2
2