ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...
    • React v19 useOptimistic wrapper for streaming search results. Provides optimistic updates so the UI reflects new products the instant they arrive, before the full search has completed. React automatically rolls back the optimistic state if a transition that produced it is interrupted or errors.

      Parameters

      • confirmedResults: Product[]

        The server-confirmed product list (source of truth)

      Returns {
          results: Product[];
          addResult: (product: Product) => void;
          addResultsBatch: (products: Product[]) => void;
      }

      An object with the current results array, an addResult function for single products, and addResultsBatch for bulk inserts.

      const { results, addResult } = useOptimisticResults(searchResults);

      for await (const product of stream) {
      addResult(product); // UI updates immediately
      }
      // results => [{ ...product, id: 0 }, { ...product, id: 1 }, ...]
      export function useOptimisticResults(confirmedResults: Product[]) {
      const [optimisticResults, addOptimisticResult] = useOptimistic(
      confirmedResults,
      (state: Product[], newProduct: Product) => {
      return [...state, { ...newProduct, id: state.length }];
      },
      );

      /**
      * Optimistically append a single product to the results list.
      * The entry appears in the UI instantly and is later reconciled
      * when `confirmedResults` updates.
      * @param product - The product to add
      * @source
      */
      const addResult = (product: Product) => {
      addOptimisticResult(product);
      };

      /**
      * Optimistically append multiple products at once.
      * Useful when several results arrive in the same tick.
      * @param products - Array of products to add
      * @example
      * ```ts
      * addResultsBatch([productA, productB]);
      * // results => [...existing, productA, productB]
      * ```
      * @source
      */
      const addResultsBatch = (products: Product[]) => {
      products.forEach((product) => addOptimisticResult(product));
      };

      return {
      results: optimisticResults,
      addResult,
      addResultsBatch,
      };
      }