Advertisement
fabiobiondi

React Pro - Real World App - Ch8. 06 - Separare il reducer dalla UI

Mar 19th, 2023
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // src/pages/cms/products/CMSProductsPage.tsx
  2. import { useReducer } from "react"
  3. import { get } from '@/services/products/products.api';
  4. import { initialState, productsReducer } from '@/services/products/products.reducer';
  5.  
  6. export function CMSProductsPage() {
  7.   const [state, dispatch] = useReducer(productsReducer, initialState);
  8.  
  9.   async function getProductsHandler() {
  10.     dispatch({ type: 'pending', payload: true } );
  11.     const res = await get();
  12.     dispatch({ type: 'productsGetSuccess', payload: res.items})
  13.   }
  14.  
  15.   return (
  16.     <div>
  17.       <h1 className="title">CMS</h1>
  18.  
  19.       Pagina Prodotti
  20.  
  21.       <hr className="my-8"/>
  22.  
  23.       {state.pending && <div>loading...</div>}
  24.  
  25.       <button className="btn primary" onClick={getProductsHandler}>GET</button>
  26.  
  27.       <pre>{JSON.stringify(state, null, 2)}</pre>
  28.     </div>
  29.   )
  30. }
  31.  
  32.  
  33.  
  34.  
  35. // services/products/products.reducer.ts
  36. import { Product } from '@/model/product';
  37. import { ProductsActions } from '@/services/products/products.actions';
  38.  
  39. export interface ProductsState {
  40.   products: Product[];
  41.   pending: boolean;
  42. }
  43.  
  44. export const initialState: ProductsState = {
  45.   pending: false,
  46.   products: []
  47. };
  48.  
  49. export function productsReducer(state: ProductsState, action: ProductsActions) {
  50.   switch (action.type) {
  51.     case 'pending':
  52.       return { ...state, pending: action.payload };
  53.     case 'productsGetSuccess':
  54.       return { pending: false, products: action.payload}
  55.   }
  56.   return state;
  57. }
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement