Advertisement
fabiobiondi

React Pro - Real World App - Ch8. 01 - 01. da useState a useReducer - Parte 3

Mar 19th, 2023
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { get } from '@/services/products/products.api';
  2. import { useReducer } from 'react';
  3.  
  4. function productsReducer(state: any, action: any) {
  5.   switch (action.type) {
  6.     case 'pending':
  7.       return { pending: true }
  8.   }
  9.   return state;
  10. }
  11.  
  12.  
  13. export function CMSProductsPage() {
  14.   const [state, dispatch] = useReducer(productsReducer, { pending: false });
  15.  
  16.   async function getProductsHandler() {
  17.     dispatch({ type: 'pending', payload: true })
  18.   }
  19.  
  20.   return (
  21.     <div>
  22.       <h1 className="title">CMS</h1>
  23.  
  24.       <hr className="my-8"/>
  25.  
  26.       { state.pending && <div>Loading</div>}
  27.  
  28.       <button
  29.         className="btn primary"
  30.         onClick={getProductsHandler}>get products</button>
  31.  
  32.       <pre>{JSON.stringify(state, null, 2)}</pre>
  33.  
  34.     </div>
  35.   )
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement