Advertisement
fabiobiondi

React Pro - Real World App - Ch8. 03 - Typed State

Mar 19th, 2023
898
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. // NEW
  7. export type ProductsState = {
  8.   products: Product[];
  9.   pending: boolean;
  10. }
  11.  
  12. // NEW
  13. function productsReducer(state: ProductsState, action: any) {
  14.   switch (action.type) {
  15.     case 'pending':
  16.       return { ...state, pending: action.payload };
  17.     case 'productsGetSuccess':
  18.       return { pending: false, products: action.payload}
  19.   }
  20.   return state;
  21. }
  22.  
  23. export const initialState = { pending: false, products: [] };
  24.  
  25. export function CMSProductsPage() {
  26.   const [state, dispatch] = useReducer(productsReducer, initialState);
  27.  
  28.   async function getProductsHandler() {
  29.     dispatch({ type: 'pending', payload: true } );
  30.     const res = await get();
  31.     dispatch({ type: 'productsGetSuccess', payload: res.items})
  32.   }
  33.  
  34.   return (
  35.     <div>
  36.       <h1 className="title">CMS</h1>
  37.  
  38.       Pagina Prodotti
  39.  
  40.       <hr className="my-8"/>
  41.  
  42.       {state.pending && <div>loading...</div>}
  43.  
  44.       <button className="btn primary" onClick={getProductsHandler}>GET</button>
  45.  
  46.       <pre>{JSON.stringify(state, null, 2)}</pre>
  47.     </div>
  48.   )
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement