
先程の続きで、Profile Reducerの作成とユーザーの現在のprofileをgetする、ということを行いました。Profile Reducer & action 仕様で、バックエンドにリクエストを行い、componentsを通じてデータを送る、ということが目的です。
①新しくsrc/reducers/profile.jsファイルを作成する
プロフィール情報をgetできるよう、新しいファイルprofile.jsをreducers内に作成しました。
profiles(複数)の部分が[] (空欄のブラケット)になっているのは、リストとして表示するためです。
- import { GET_PROFILE, PROFILE_ERROR } from "../actions/types";
- const initialState = {
- profile: null,
- profiles: [], //profile listing page
- repos: [],
- loading: true,
- error: {}
- };
- export default function(state = initialState, action) {
- const { type, payload } = action;
- switch (type) {
- case GET_PROFILE:
- return {
- ...state,
- profile: payload,
- loading: false
- };
- case PROFILE_ERROR:
- return {
- ...state,
- error: payload,
- loading: false
- };
- default:
- return state;
- }
- }
②src/reducers/index.jsへコードを書き足す
profileについての情報を書き足しました。
- import { combineReducers } from "redux";
- import alert from "./alert";
- import auth from "./auth";
- import profile from "./profile";
- export default combineReducers({
- alert,
- auth,
- profile
- });
③src/actions/types.jsへコードを書き足す
types.jsにも、GET_PROFILE, PROFILE_ERRORをexportできるようコードを書き足します。この作業はルーティン化しているので慣れてきました。
- export const GET_PROFILE = "GET_PROFILE";
- export const PROFILE_ERROR = "PROFILE_ERROR";
④src/actions/profile.jsという新しいファイルを作成
actionsにprofile.jsファイルを作成しました。こちらも3行目のsetAlertの部分でエラーが出てしまったので、//eslint-disable-next-lineで応急処置をしています。(後ほど外す予定)
- import axios from "axios";
- // eslint-disable-next-line
- import { setAlert } from "./alert";
- import { GET_PROFILE, PROFILE_ERROR } from "./types";
- // Get current users profile
- export const getCurrentProfile = () => async dispatch => {
- try {
- const res = await axios.get("/api/profile/me");
- dispatch({
- type: GET_PROFILE,
- payload: res.data
- });
- } catch (err) {
- dispatch({
- type: PROFILE_ERROR,
- payload: { msg: err.response.statusText, status: err.response.status }
- });
- }
- };
最後にlocalhostとRedux devtools extensionで動作確認したのですが、全て問題なく動いたのでOKとしました!(Git Bashの方はcomplied with warningなのでまだまだ対策が必要そうです。)
現在使用している教材と学習時間:本日の学習時間2.5時間
Udemy:MERN Stack Front To Back: Full Stack React, Redux & Node.js by Brad Traversy
★Section9:Dashboard & Profile Management
-Lec 44 Protected Route For Dashboard
-Lec 45 Profile Reducer & Get Current Profile (このブログ記事に書いた内容。ここまで完了。)
進捗状況:63%
学習時間2.5時間
~本日は休みにしている教材~
Udemy:The Complete Web Developer: Zero to Mastery by Andrei Neagoie
進捗状況: 92%
★参考にした本★
「React.js & Next.js超入門」掌田津耶乃 (秀和システム)
Section4-1: Reduxを使ってみよう
★参照記事★
Quiita参照記事⇒[axios] axios の導入と簡単な使い方