Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // src/pages/cms/products/CMSProductsPage.tsx
- import { useReducer } from "react"
- import { get } from '@/services/products/products.api';
- import { initialState, productsReducer } from '@/services/products/products.reducer';
- export function CMSProductsPage() {
- const [state, dispatch] = useReducer(productsReducer, initialState);
- async function getProductsHandler() {
- dispatch({ type: 'pending', payload: true } );
- const res = await get();
- dispatch({ type: 'productsGetSuccess', payload: res.items})
- }
- return (
- <div>
- <h1 className="title">CMS</h1>
- Pagina Prodotti
- <hr className="my-8"/>
- {state.pending && <div>loading...</div>}
- <button className="btn primary" onClick={getProductsHandler}>GET</button>
- <pre>{JSON.stringify(state, null, 2)}</pre>
- </div>
- )
- }
- // services/products/products.reducer.ts
- import { Product } from '@/model/product';
- import { ProductsActions } from '@/services/products/products.actions';
- export interface ProductsState {
- products: Product[];
- pending: boolean;
- }
- export const initialState: ProductsState = {
- pending: false,
- products: []
- };
- export function productsReducer(state: ProductsState, action: ProductsActions) {
- switch (action.type) {
- case 'pending':
- return { ...state, pending: action.payload };
- case 'productsGetSuccess':
- return { pending: false, products: action.payload}
- }
- return state;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement