죽이죽이
React : Redux 비동기 처리 본문
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 |