import { createReducer } from '@reduxjs/toolkit'; import { Categories, Product, Products } from '@interfaces'; import { getAllCategoriesThunk, getAllProductsThunk } from './thunk'; export interface HomeState { products: Products[]; isLoading: boolean; error: string | null; categories: Categories[]; } const initialState: HomeState = { products: [], isLoading: false, error: null, categories: [], }; const homeReducer = createReducer(initialState, builder => { builder .addCase(getAllProductsThunk.pending, state => { state.isLoading = true; state.error = null; }) .addCase(getAllProductsThunk.fulfilled, (state, action) => { // Handle the API returning { products, meta } state.products = action.payload?.products || (Array.isArray(action.payload) ? action.payload : []); state.isLoading = false; }) .addCase(getAllProductsThunk.rejected, (state, action) => { state.isLoading = false; state.error = action.payload || 'Failed to fetch products'; }) .addCase(getAllCategoriesThunk.fulfilled, (state, action) => { state.categories = action.payload || []; state.isLoading = false; }) .addCase(getAllCategoriesThunk.rejected, (state, action) => { state.isLoading = false; state.error = (action.payload as string) || 'Failed to fetch categories'; }); }); export default homeReducer;