37 lines
1005 B
TypeScript
37 lines
1005 B
TypeScript
import { createReducer } from '@reduxjs/toolkit';
|
|
import { Product, Products } from '@interfaces';
|
|
import { getAllProductsThunk } from './thunk';
|
|
|
|
export interface HomeState {
|
|
products: Products[];
|
|
isLoading: boolean;
|
|
error: string | null;
|
|
}
|
|
|
|
const initialState: HomeState = {
|
|
products: [],
|
|
isLoading: false,
|
|
error: null,
|
|
};
|
|
|
|
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';
|
|
});
|
|
});
|
|
|
|
export default homeReducer;
|