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

redux-thunk

by zieunee 2022. 2. 3.
반응형

store.js

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

const store = createStore(todoApp, composeWithDevTools(applyMiddleware(thunk)));
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)); 
        }
    }
}

UserListContainer.jsx

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

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

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

    return <UserList users={users} getUsers={getUsers} />
}
반응형

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

eject 대신 webpack설치하기  (0) 2022.02.05
redux-promise-middleware  (0) 2022.02.04
redux-devtools  (0) 2022.02.02
리덕스 미들웨어  (0) 2022.02.01
Async Action  (0) 2022.01.31