Advertisement
fabiobiondi

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

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