본문 바로가기
개발(라이브러리,프레임워크)/react.js & react native

redux-promise-middleware

by zieunee 2022. 2. 4.
반응형

redux-promise-middleware 사용하기 

npm install redux-promise-middleware

users.js

import { GET_USERS_FAIL, GET_USERS_FULLFILLED, GET_USERS_PENDING, GET_USERS_REJECTED, GET_USERS_START, GET_USERS_SUCCESS } from "../actions";

const initialState =  {
    loading: false,
    data: [],
    error: null
};

export default function users(state = initialState, action) {
    if(action.type === GET_USERS_START || action.type === GET_USERS_PENDING){
        return {
            ...state,
            loading: true,
            error: null,
        };
    }
    if(action.type === GET_USERS_SUCCESS){
        return {
            ...state,
            loading: false,
            data: action.data,
        };
    }
    if(action.type === GET_USERS_FULLFILLED){
        return {
            ...state,
            loading: false,
            data: action.payload,
        };
    }
    if(action.type === GET_USERS_FAIL){
        return {
            ...state,
            loading: false,
            error: action.error,
        };
    }
    if(action.type === GET_USERS_REJECTED){
        return {
            ...state,
            loading: false,
            error: action.payload,
        };
    }
    return state;
}

userListContainer.jsx

import { useCallback } from "react";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux"
import UserList from "../components/UserList"
import { getUsersPromise, getUsersThunk } from "../redux/actions";

export default function UserListContainer(){
    const users = useSelector((state) => state.users.data);
    const dispatch = useDispatch();

    const getUsers = useCallback(()=> {
        dispatch(getUsersPromise())
    },[dispatch]);

    return <UserList users={users} getUsers={getUsers} />
}

store.j

import { applyMiddleware, createStore } from 'redux'
import todoApp from './reducers/reducer'
import {composeWithDevTools}  from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware'

//applyMiddleware는 함수를 리턴할떄만 반응하고 객체를 리턴할때는 그대로 동작한다.
const store = createStore(todoApp, composeWithDevTools(applyMiddleware(thunk,promise)));
export default store;

actions.js

import axios from "axios";

export const ADD_TODO = "ADD_TODO"
export const COMPLETE_TODO = 'COMPLETE_TODO';

// {type : ADD_TODO , text: '할일'}
export function addTodo(text) {
    return {
        type: ADD_TODO,
        text,
    };
}
// {type : COMPLETE_TODO , text: 3} > 완성된 index 값
export function completeTodo(index) {
    return {
        type: COMPLETE_TODO,
        index,
    };
}
export const SHOW_ALL = 'SHOW_ALL';
export const SHOW_COMPLETE = 'SHOW_COMPLETE';

export function showAll() {
    return {type:SHOW_ALL};
}
export function showComplete() {
    return {type: SHOW_COMPLETE};
}

//users
//깃헙 api 호출 시작
export const GET_USERS_START = 'GET_USERS_START';
//깃헙 api 호출이 성공적으로 들어온 경우
export const GET_USERS_SUCCESS = 'GET_USERS_SUCCESS';
//깃헙 api 호출이 실패한 경우
export const GET_USERS_FAIL = 'GET_USERS_FAIL';

export function getUsersStart() {
    return {
        type: GET_USERS_START
    };
}
export function getUsersSuccess(data) {
    return {
        type: GET_USERS_SUCCESS,
        data,
    };
}
export function getUsersFail(error) {
    return {
        type: GET_USERS_FAIL,
        error,
    };
}

export function getUsersThunk(){
    //함수로 리턴
    //dispatch는 원래 container에서 처리하고 있는데 이제는 액션 생성하는쪽에서 실행시킨다.
    return async (dispatch)=>{
        try {
            dispatch(getUsersStart()); 
            const res = await axios.get('<https://api.github.com/users>');
            dispatch(getUsersSuccess(res.data)); ;
        }catch(error){
            dispatch(getUsersFail(error)); 
        }
    }
}
const GET_USERS = 'GET_USERS'

export const GET_USERS_PENDING = 'GET_USERS_PENDING'
export const GET_USERS_FULLFILLED = 'GET_USERS_FULLFILLED'
export const GET_USERS_REJECTED = 'GET_USERS_REJECTED'
export function getUsersPromise(){
    return {
        type: GET_USERS,
        payload: async() => {
            const res = await axios.get('<https://api.github.com/users>');
            return res.data;
        }
    }
}
반응형

'개발(라이브러리,프레임워크) > react.js & react native' 카테고리의 다른 글

devServer proxy 설정  (0) 2022.02.06
eject 대신 webpack설치하기  (0) 2022.02.05
redux-thunk  (0) 2022.02.03
redux-devtools  (0) 2022.02.02
리덕스 미들웨어  (0) 2022.02.01