import { createReducer } from '@reduxjs/toolkit'; import { Products } from '@interfaces'; import { getProductsByCategoryThunk } from './thunk'; export interface SearchState { products: Products[]; isLoading: boolean; error: string | null; selectedCategoryId: string | undefined; selectedCategoryName: string | undefined; } const initialState: SearchState = { products: [], isLoading: false, error: null, selectedCategoryId: undefined, selectedCategoryName: undefined, }; const searchReducer = createReducer(initialState, builder => { builder .addCase(getProductsByCategoryThunk.pending, (state, action) => { state.isLoading = true; state.error = null; // Store the categoryId that was requested so the UI can track it state.selectedCategoryId = action.meta.arg; }) .addCase(getProductsByCategoryThunk.fulfilled, (state, action) => { state.isLoading = false; state.products = action.payload?.products || (Array.isArray(action.payload) ? action.payload : []); }) .addCase(getProductsByCategoryThunk.rejected, (state, action) => { state.isLoading = false; state.error = action.payload || 'Failed to fetch products'; }); }); export default searchReducer;