ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • react ( Udemy강의 ) - 7-2. Redux
    ReactJS 2022. 5. 14. 15:03

    리덕스 + 비동기

    - 리듀서 함수는 반드시 순수함수여야 하며, 부수 효과가 없고 동기식이어야 한다.

    - 절대 리듀서 내부에서 부수 효과( 동기 비동기 )를 수행하지마시오. 

     

     

     

    Fat Reducers VS Fat Components VS Fat Actions

         Synchronous, side-effect free code (data transformation) : Prefer Reducers

                                                                                 Avoid Action Creators or Components

         Async code or code with side-effects : Prefer Action Creators or Components

                                                                 Never use Reducers

     

     

    side-effects and async task를 어디서  처리해야하는가?

    1. Inside the components ( useEffect() ) : 우리가 흔히 사용하는 방법

    2. Inside the action creators : store를 이용하는 방법

     

    Action Creators

    Thunk

         - 다른 작업이 완료될 때까지 작업을 지연시키는 단순한 함수

         - 작업 객체를 즉시 반환하지 않는 작업 크리에이터의 작성을 위해 썽크로 작업 크리에이터를 작성

         - 결국 작업을 반환하는 다른 함수를 반환

         - 우리가 만들고자 했던 실제 작업 객체를 디스패치하기 전에 다른 코드를 실행할 수 있다.

     

    * 리덕스 툴킷의 장점 : 유형 프로퍼티가 있는 작업 개체만 허용하는 것이 아니라 함수를 반환하는 작업 크리에이터도 허용, 그리고 실제로 작업 객체가 아닌 함수인 작업을 디스패치하는 것으로 확인되면 해당 함수를 자동으로 실행

    1. App.js

    import { sendCartData } from './store/cart-slice';
    
    useEffect(() => {
        if (isInitial) {
          isInitial = false;
          return;
        }
        dispatch(sendCartData(cart));
      }, [cart, dispatch]);

    2. cart-slice 

    // 작업 크리에이터 - 리덕스 툴킷은 이러한 리듀서 메소드에 대해 작업 크리에이터를 자동으로 생성
    export const sendCartData = (cart) => {
        // 자동으로 디스패치 인수를 줌
      return async (dispatch) => {
        dispatch(
          uiActions.showNotification({
            status: "pending",
            title: "Sending...",
            message: "Sending cart data!",
          })
        );
        const sendRequest = async () => {
          const response = await fetch(
            "https://react-http-f8b8f-default-rtdb.firebaseio.com/cart.json",
            {
              method: "PUT",
              body: JSON.stringify(cart),
            }
          );
    
          if (!response.ok) {
            throw new Error("Sending cart data failed.");
          }
        };
    
        try {
          await sendRequest();
    
          dispatch(
            uiActions.showNotification({
              status: "success",
              title: "Success!",
              message: "Sent cart data successfully!",
            })
          );
        } catch (error) {
          dispatch(
            uiActions.showNotification({
              status: "error",
              title: "Error!",
              message: "Sent cart data successfully!",
            })
          );
        };
      };
    };

     

    Redux DevTools

         - 크롬 확장 프로그램 Redux DevTools, 리덕스 디버깅을 더 쉽게 도와줌

         - 리덕스 툴킷 없이 리덕스를 사용할 때는 리덕스 데브툴이 작동하도록 몇 가지 추가 코드 설정

     

     

     

     

     

    댓글

Designed by Tistory.