Guest User

Untitled

a guest
Sep 21st, 2025
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable, inject, effect } from '@angular/core';
  2. import {
  3.   signalStore,
  4.   withState,
  5.   withMethods,
  6.   patchState,
  7.   withHooks,
  8. } from '@ngrx/signals';
  9. import { HttpClient } from '@angular/common/http';
  10. import { firstValueFrom } from 'rxjs';
  11. import { Product } from './product.model';
  12.  
  13. interface ProductState {
  14.   products: Product[];
  15.   isLoading: boolean;
  16.   error: string | null;
  17. }
  18.  
  19. const initialState: ProductState = {
  20.   products: [],
  21.   isLoading: false,
  22.   error: null,
  23. };
  24.  
  25. @Injectable({
  26.   providedIn: 'root',
  27. })
  28. export class ProductStore extends signalStore(
  29.   withState(initialState),
  30.   withMethods((store, http = inject(HttpClient)) => ({
  31.     async loadProducts(): Promise<void> {
  32.       patchState(store, { isLoading: true, error: null });
  33.       try {
  34.         const res = await firstValueFrom(
  35.           http.get<{ products: Product[] }>('https://dummyjson.com/products')
  36.         );
  37.         patchState(store, {
  38.           products: res.products,
  39.           isLoading: false,
  40.           error: null,
  41.         });
  42.       } catch (error) {
  43.         patchState(store, {
  44.           products: [],
  45.           isLoading: false,
  46.           error:
  47.             error instanceof Error ? error.message : 'Failed to load products',
  48.         });
  49.       }
  50.     },
  51.  
  52.     addProduct(newProduct: Product): void {
  53.       const currentProducts = store.products();
  54.       const exists = currentProducts.some((p) => p.id === newProduct.id);
  55.       if (exists) {
  56.         patchState(store, {
  57.           error: `Product with ID ${newProduct.id} already exists`,
  58.         });
  59.         return;
  60.       }
  61.       patchState(store, {
  62.         products: [...currentProducts, newProduct],
  63.         error: null,
  64.       });
  65.     },
  66.  
  67.     updateProduct(productId: number, updatedProduct: Product): void {
  68.       const currentProducts = store.products();
  69.       const productIndex = currentProducts.findIndex((p) => p.id === productId);
  70.       if (productIndex === -1) {
  71.         patchState(store, {
  72.           error: `Product with ID ${productId} not found`,
  73.         });
  74.         return;
  75.       }
  76.       const updatedProducts = [...currentProducts];
  77.       updatedProducts[productIndex] = updatedProduct;
  78.       patchState(store, {
  79.         products: updatedProducts,
  80.         error: null,
  81.       });
  82.     },
  83.  
  84.     deleteProduct(productId: number): void {
  85.       const currentProducts = store.products();
  86.       const exists = currentProducts.some((p) => p.id === productId);
  87.       if (!exists) {
  88.         patchState(store, {
  89.           error: `Product with ID ${productId} not found`,
  90.         });
  91.         return;
  92.       }
  93.       patchState(store, {
  94.         products: currentProducts.filter((p) => p.id !== productId),
  95.         error: null,
  96.       });
  97.     },
  98.  
  99.     findProduct(productId: number): Product | undefined {
  100.       return store.products().find((p) => p.id === productId);
  101.     },
  102.  
  103.     productExists(productId: number): boolean {
  104.       return store.products().some((p) => p.id === productId);
  105.     },
  106.  
  107.     clearError(): void {
  108.       patchState(store, { error: null });
  109.     },
  110.  
  111.     reset(): void {
  112.       patchState(store, initialState);
  113.     },
  114.   })),
  115.   // ✅ AUTOMATIC SORTING using withHooks and effect
  116.   withHooks({
  117.     onInit(store) {
  118.       effect(() => {
  119.         const products = store.products();
  120.         // Only sort if products exist and we have more than one product
  121.         if (products && products.length > 1) {
  122.           // Check if the array is already sorted to avoid unnecessary updates
  123.           const sorted = [...products].sort((a, b) =>
  124.             a.title.localeCompare(b.title)
  125.           );
  126.           // Only update if the order actually changed
  127.           const needsSorting = products.some(
  128.             (prod, index) => prod.id !== sorted[index]?.id
  129.           );
  130.           if (needsSorting) {
  131.             console.log('Products not sorted, auto-sorting now...');
  132.             patchState(store, { products: sorted });
  133.           }
  134.         }
  135.       });
  136.     },
  137.   })
  138. ) {}
  139.  
Advertisement
Add Comment
Please, Sign In to add comment