Redux Middleware 사용하기

이시원·2022년 9월 15일
0

Redux 공부

목록 보기
8/12
post-thumbnail

API 호출하는 부분을 Redux Middleware을 사용해서 바꿔보기
  • Component
    • dispatch가 Middleware을 거쳐서 reducer로 간다.
    • searchQuery 값을 매개변수를 통해 getProducts 함수로 전달
  const dispatch = useDispatch();

  const getProducts = async () => {
    let searchQuery = query.get("q") || "";
    dispatch(productAction.getProducts(searchQuery));
  };

  • Middleware
    • Middleware 함수
    • 함수를 return
    • 이 함수는 항상 dispatch와 getState 매개변수를 가진다.
    • dispatch : Action을 줌
    • getState : 현재의 state 정보를 받아볼 수 있다.

function getProducts(searchQuery) {
  return async (dispatch, getState) => {
    let url = `https://my-json-server.typicode.com/mynameisleesiwon/hnm-react-router-practice/products?q=${searchQuery}`;
    let response = await fetch(url);
    let data = await response.json();

    // reducer로 보냄
    dispatch({ type: "GET_PRODUCT_SUCCESS", payload: { data } });
  };
}

export const productAction = { getProducts };

  • reducer
let initialState = {
  productList: [],
};

function productReducer(state = initialState, action) {
  let { type, payload } = action;
  switch (type) {
    case "GET_PRODUCT_SUCCESS":
      return { ...state, productList: payload.data };
    default:
      return { ...state };
  }
}

export default productReducer;

  • Component
import React, { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { Container, Row, Col } from "react-bootstrap";
import ProductCard from "../component/ProductCard";
import { productAction } from "../redux/actions/productAction";
import { useDispatch, useSelector } from "react-redux/es/exports";

const ProductAll = () => {
  const productList = useSelector((state) => state.productList);
  const [query, setQuery] = useSearchParams();
  const dispatch = useDispatch();

  const getProducts = async () => {
    let searchQuery = query.get("q") || "";
    console.log("쿼리값은?", searchQuery);
    dispatch(productAction.getProducts(searchQuery));
  };
  
  // api호출은 useEffect에서
  useEffect(() => {
    getProducts();
  }, [query]);

  return (
    <div>
      {/* Container : 아이템을 가운데 둘 수 있게 해준다 */}
      <Container>
        <Row>
          {productList &&
            productList.map((menu) => (
              <Col lg={3}>
                {" "}
                <ProductCard item={menu} />
              </Col>
            ))}
        </Row>
      </Container>
    </div>
  );
};

export default ProductAll;
profile
코딩공부

0개의 댓글