Advertisement
fabiobiondi

React Pro - Real World App - Ch8. 02 - Products API

Mar 19th, 2023
1,004
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // src/pages/cms/products/CMSProductsPage.tsx
  2. import { get } from '@/services/products/products.api';
  3. import { useReducer } from "react"
  4.  
  5. function productsReducer(state: any, action: any) {
  6.   switch (action.type) {
  7.     case 'pending':
  8.       return { ...state, pending: action.payload };
  9.     case 'getProductsSuccess':
  10.       return { pending: false, products: action.payload}
  11.   }
  12.   return state;
  13. }
  14.  
  15. export const initialState = { pending: false, products: [] };
  16.  
  17. export function CMSProductsPage() {
  18.   const [state, dispatch] = useReducer(productsReducer, initialState);
  19.  
  20.   async function getProductsHandler() {
  21.     dispatch({ type: 'pending', payload: true } );
  22.     const res = await get();
  23.     dispatch({ type: 'getProductsSuccess', payload: res.items})
  24.   }
  25.  
  26.   return (
  27.     <div>
  28.       <h1 className="title">CMS</h1>
  29.  
  30.       Pagina Prodotti
  31.  
  32.       <hr className="my-8"/>
  33.  
  34.       {state.pending && <div>loading...</div>}
  35.  
  36.       <button className="btn primary" onClick={getProductsHandler}>GET</button>
  37.  
  38.       <pre>{JSON.stringify(state, null, 2)}</pre>
  39.     </div>
  40.   )
  41. }
  42.  
  43.  
  44.  
  45.  
  46.  
  47. // services/products/products.api.ts
  48. import { Product } from '@/model/product';
  49. import { pb } from '../../pocketbase';
  50.  
  51. export function get() {
  52.   return pb.collection('products').getList<Product>();
  53. }
  54.  
  55. export function remove(id: string) {
  56.   return pb.collection('products').delete(id);
  57. }
  58.  
  59. export function add(product: Partial<Product>) {
  60.   return pb.collection('products').create<Product>(product);
  61. }
  62.  
  63. export function edit(product: Partial<Product>) {
  64.   return pb.collection('products').update<Product>(product.id!, product);
  65. }
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement