Advertisement
fabiobiondi

React Pro - Real World App - Ch8. 04 - Typed Actions

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