добавил api клиент, исправил стор, слайсы для продуктов и категорий
This commit is contained in:
1 parent
86f53ba61f
commit
181a24571c
8 files changed
+121
-166
No files matched your search
@@ -0,0 +1,9 @@
|
||||
import axios from "axios";
|
||||
|
||||
export const API_BASE = g;/* process.env.REACT_APP_API_BASE || "";*/
|
||||
const client = axios.create({
|
||||
baseURL: API_BASE,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
export default client;
|
||||
@@ -1,5 +1,7 @@
|
||||
import { configureStore } from "@reduxjs/toolkit";
|
||||
import catalogReducer from "../features/catalog/catalogSlice";
|
||||
import catalogReducer from "../features/catalog/productsSlice";
|
||||
import categoriesReducer from "../features/catalog/categoriesSlice"
|
||||
import productsReducer from "../features/catalog/productsSlice"
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import React, { useEffect } from "react";
|
||||
import styles from "./SidebarCategories.module.css";
|
||||
import { useAppDispatch, useAppSelector } from "../../app/hooks";
|
||||
import { fetchCategories, setSelectedCategory } from "./categoriesSlice";
|
||||
import { fetchProductsByCategory, setFilters, setPage } from "./productsSlice";
|
||||
|
||||
const SidebarCategories: React.FC = () => {
|
||||
return(
|
||||
<>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
|
||||
import type {PayloadAction} from "@reduxjs/toolkit";
|
||||
import { fetchCategoryProducts, fetchCategories } from "../../api/catalogApi";
|
||||
import type { Product } from "../../types/product";
|
||||
import axios from "axios";
|
||||
|
||||
interface CatalogState {
|
||||
products: Product[];
|
||||
filtered: Product[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
filters: Record<string, string[]>;
|
||||
currentCategory: string | null;
|
||||
}
|
||||
|
||||
const initialState: CatalogState = {
|
||||
products: [],
|
||||
filtered: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
filters: {},
|
||||
currentCategory: null,
|
||||
};
|
||||
|
||||
export const fetchProductsByCategory = createAsyncThunk(
|
||||
"products/fetchProductsByCategory",
|
||||
async (categoryId: number) => {
|
||||
const res = await axios.get(`/api/products?category=${categoryId}`);
|
||||
return res.data;
|
||||
}
|
||||
);
|
||||
|
||||
export const fetchCategoryParameters = createAsyncThunk(
|
||||
"products/fetchCategoryParametrs",
|
||||
async (categoryId: number) => {
|
||||
const res = await axios.get(`/api/category-params/${categoryId}`);
|
||||
return res.data;
|
||||
}
|
||||
)
|
||||
|
||||
const catalogSlice = createSlice({
|
||||
name: "catalog",
|
||||
initialState,
|
||||
reducers: {
|
||||
setFilter(state, action: PayloadAction<{ name: string; value: string }>) {
|
||||
const { name, value } = action.payload;
|
||||
const active = state.filters[name] || [];
|
||||
state.filters[name] = active.includes(value)
|
||||
? active.filter((v) => v !== value)
|
||||
: [...active, value];
|
||||
},
|
||||
applyFilters(state) {
|
||||
state.filtered = state.products.filter((p) =>
|
||||
Object.entries(state.filters).every(([key, values]) =>
|
||||
values.length ? values.includes(p[key as keyof Product] as string) : true
|
||||
)
|
||||
);
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
builder
|
||||
.addCase(fetchProductsByCategory.pending, (state) => {
|
||||
state.loading = true;
|
||||
state.error = null;
|
||||
})
|
||||
.addCase(fetchProductsByCategory.fulfilled, (state, action) => {
|
||||
state.loading = false;
|
||||
state.products = action.payload;
|
||||
state.filtered = action.payload;
|
||||
state.error = null;
|
||||
})
|
||||
.addCase(fetchProductsByCategory.rejected, (state, action) => {
|
||||
state.loading = false;
|
||||
state.error = action.error.message || "Ошибка загрузки товаров";
|
||||
state.products = [];
|
||||
state.filtered = [];
|
||||
})
|
||||
.addCase(fetchCategoryParameters.pending, (state) => {
|
||||
state.loading = true;
|
||||
state.error = null;
|
||||
})
|
||||
.addCase(fetchCategoryParameters.fulfilled, (state, action) => {
|
||||
state.loading = false;
|
||||
state.filters = action.payload
|
||||
})
|
||||
.addCase(fetchCategoryParameters.rejected, (state, action) => {
|
||||
state.loading = false;
|
||||
state.error = action.error.message || "Ошибка загрузки параметров категории";
|
||||
state.filters = {};
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const { setFilter, applyFilters } = catalogSlice.actions;
|
||||
export default catalogSlice.reducer;
|
||||
@@ -1,69 +0,0 @@
|
||||
import React from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { setFilter, applyFilters } from "./catalogSlice";
|
||||
import styles from "./Catalog.module.css";
|
||||
import type { Category } from "../../types/categories";
|
||||
import type { CategoryAtributes } from "../../types/categories";
|
||||
import type { CategoryAtrVals } from "../../types/categories";
|
||||
|
||||
interface Props{
|
||||
categories: Category[];
|
||||
atributes: CategoryAtributes[]
|
||||
atrVals: CategoryAtrVals[];
|
||||
}
|
||||
|
||||
const CatalogSidebar: React.FC<Props> = ({categories, atributes, atrVals}) => {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const handleFilterChange = (name: string, value: string) => {
|
||||
dispatch(setFilter({ name, value }));
|
||||
dispatch(applyFilters());
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={styles.sidebar}>
|
||||
<h3>ПАРАМЕТРЫ</h3>
|
||||
<div className={styles.filterGroup}>
|
||||
<p>размер:</p>
|
||||
{atributes.map((a) => (
|
||||
<>
|
||||
<p>{a.name}</p>
|
||||
{atrVals.map((b) => (
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange(`${a.name}`, `${b.val}`)} /> <p>{b.val}</p>
|
||||
</label>
|
||||
))}
|
||||
</>
|
||||
))}
|
||||
|
||||
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("size", "110х2,2х500")} /> 110х2,2х500
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("size", "110х2,2х1000")} /> 110х2,2х1000
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("size", "110х2,2х1500")} /> 110х2,2х1500
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("size", "110х2,2х2000")} /> 110х2,2х2000
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("size", "110х2,2х3000")} /> 110х2,2х3000
|
||||
</label>
|
||||
</div>
|
||||
<div className={styles.filterGroup}>
|
||||
<p>Форма выпуска:</p>
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("form", "Наборы")} /> Наборы
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" onChange={() => handleFilterChange("form", "Поштучно")} /> Поштучно
|
||||
</label>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
export default CatalogSidebar;
|
||||
@@ -0,0 +1,95 @@
|
||||
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
|
||||
import type {PayloadAction} from "@reduxjs/toolkit";
|
||||
import client from "../../api/client";
|
||||
import type { Product } from "../../types/product";
|
||||
import axios from "axios";
|
||||
|
||||
interface FetchParams {
|
||||
categoryId: number;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
filters?: Record<string, string | number | (string | number)[]>;
|
||||
}
|
||||
|
||||
export const fetchProductsByCategory = createAsyncThunk(
|
||||
"products/fetchByCategory",
|
||||
async (params: FetchParams) => {
|
||||
const { categoryId, page = 1, limit = 9, filters} = params;
|
||||
const qp = new URLSearchParams();
|
||||
qp.append("categoryId", String(categoryId));
|
||||
qp.append("page", String(page));
|
||||
qp.append("limit", String(limit));
|
||||
if (filters) {
|
||||
Object.keys(filters).forEach((k) => {
|
||||
const v = filters[k];
|
||||
if (Array.isArray(v)) qp.append(k, v.join(","));
|
||||
else qp.append(k, String(v));
|
||||
});
|
||||
}
|
||||
const res = await client.get(`/products?${qp.toString()}`);
|
||||
// ожидаем { items: Product[], total: number, page: number, limit: number }
|
||||
return res.data;
|
||||
}
|
||||
);
|
||||
|
||||
interface ProductsState {
|
||||
items: Product[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
filtersApplied: Record<string, (string|number)[]>;
|
||||
}
|
||||
|
||||
const initialState: ProductsState = {
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
limit: 9,
|
||||
loading: false,
|
||||
error: null,
|
||||
filtersApplied: {},
|
||||
};
|
||||
|
||||
const slice = createSlice({
|
||||
name: "products",
|
||||
initialState,
|
||||
reducers: {
|
||||
setPage(state, action: PayloadAction<number>) {
|
||||
state.page = action.payload;
|
||||
},
|
||||
setLimit(state, action: PayloadAction<number>) {
|
||||
state.limit = action.payload;
|
||||
},
|
||||
setFilters(state, action: PayloadAction<ProductsState["filtersApplied"]>) {
|
||||
state.filtersApplied = action.payload;
|
||||
},
|
||||
resetProducts(state) {
|
||||
state.items = [];
|
||||
state.total = 0;
|
||||
state.page = 1;
|
||||
}
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
builder
|
||||
.addCase(fetchProductsByCategory.pending, (s) => {
|
||||
s.loading = true;
|
||||
s.error = null;
|
||||
})
|
||||
.addCase(fetchProductsByCategory.fulfilled, (s, a) => {
|
||||
s.loading = false;
|
||||
s.items = a.payload.items;
|
||||
s.total = a.payload.total;
|
||||
s.page = a.payload.page ?? s.page;
|
||||
s.limit = a.payload.limit ?? s.limit;
|
||||
})
|
||||
.addCase(fetchProductsByCategory.rejected, (s, a) => {
|
||||
s.loading = false;
|
||||
s.error = a.error.message ?? "Ошибка";
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const { setPage, setLimit, setFilters, resetProducts } = slice.actions;
|
||||
export default slice.reducer;
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import type { RootState } from "../../app/store";
|
||||
import { getCategoryProducts } from "../../features/catalog/catalogSlice";
|
||||
import { getCategoryProducts } from "../../features/catalog/productsSlice";
|
||||
import CatalogSidebar from "../../features/catalog/catalogeSidebar"
|
||||
import ProductGrid from "../../features/catalog/ProductGrid";
|
||||
import styles from "../../features/catalog/catalog.module.css";
|
||||
|
||||
@@ -14,3 +14,4 @@ export interface Category {
|
||||
name: string;
|
||||
atributes: CategoryAtributes[];
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user