Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

죽이죽이

React : Redux 비동기 처리 본문

React

React : Redux 비동기 처리

죽이죽이 2024. 2. 27. 21:25

Redux 비동기 처리

※ 방법 2가지



※ useEffect 사용

import { useSelector } from "react-redux";

import Cart from "./components/Cart/Cart";
import Layout from "./components/Layout/Layout";
import Products from "./components/Shop/Products";
import { useEffect } from "react";

function App() {
  const showCart = useSelector((state) => state.ui.cartIsVisible);
  const cart = useSelector((state) => state.cart);
  
  // 카드가 바뀔때마다 firebase에 데이터 저장
  useEffect(() => {
    fetch("https://test-9ba2f-default-rtdb.firebaseio.com/cart.json", {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(cart),
    });
  }, [cart]);

  return (
    <Layout>
      {showCart && <Cart />}
      <Products />
    </Layout>
  );
}

export default App;



※ Redux Toolkit Thunk 사용

export const sendCartData = (cart) => {
  return async (dispatch) => {
    try {
      const response = await fetch("https://test-9ba2f-default-rtdb.firebaseio.com/cart.json", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(cart),
      });

      if (!response.ok) {
        throw new Error("실패");
      }
    } catch (error) {
      console.error(error.message);
    }
  };
};


- 사용하는 곳

  const cart = useSelector((state) => state.cart);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(sendCartData(cart));
  }, [cart, dispatch]);

 

 

'React' 카테고리의 다른 글

React : 프로젝트 트러블 슈팅  (0) 2024.06.08
React : react-router-dom  (0) 2024.02.28
React : Redux ToolKit (RTK)  (0) 2024.02.27
React : Redux 사용하기  (0) 2024.02.27
React : Redux란?  (0) 2024.02.26