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();
dispatch({ type: "GET_PRODUCT_SUCCESS", payload: { data } });
};
}
export const productAction = { getProducts };
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;
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));
};
useEffect(() => {
getProducts();
}, [query]);
return (
<div>
{}
<Container>
<Row>
{productList &&
productList.map((menu) => (
<Col lg={3}>
{" "}
<ProductCard item={menu} />
</Col>
))}
</Row>
</Container>
</div>
);
};
export default ProductAll;