fabiobiondi

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

Mar 19th, 2023
163
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.   if (action.type === 'pending') {
  6.     return { pending: true }
  7.   }
  8.   return state;
  9. }
  10.  
  11.  
  12. export function CMSProductsPage() {
  13.   const [state, dispatch] = useReducer(productsReducer, { pending: false });
  14.  
  15.   async function getProductsHandler() {
  16.     dispatch({ type: 'pending', payload: true })
  17.   }
  18.  
  19.   return (
  20.     <div>
  21.       <h1 className="title">CMS</h1>
  22.  
  23.       <hr className="my-8"/>
  24.  
  25.       { state.pending && <div>Loading</div>}
  26.  
  27.       <button
  28.         className="btn primary"
  29.         onClick={getProductsHandler}>get products</button>
  30.  
  31.       <pre>{JSON.stringify(state, null, 2)}</pre>
  32.  
  33.     </div>
  34.   )
  35. }
  36.  
Add Comment
Please, Sign In to add comment