Files
xenia-pos-local/waiter_pwa/src/hooks/useProductCache.js
T
bonaminandClaude Opus 5.5 15bd0f5b57 feat(waiter): keep the menu's photos for offline (platform-v2 step 5.2)
Right after the menu is read the phone downloads its photos (4 at a time,
services/photoCache.js). The library's year-long immutable headers keep them
in the browser cache; the installed PWA also caches /api/media/file/ cache-
first (workbox `xenia-media`). With no connection the menu still shows them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:57:51 +02:00

75 lines
2.4 KiB
JavaScript

import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import client from '../api/client'
import db from '../db/posdb'
import { warmPhotos } from '../services/photoCache'
export const PRODUCTS_KEY = ['products']
async function fetchAndCacheProducts() {
const [prodRes, catRes] = await Promise.all([
client.get('/api/products/', { params: { sold_at: 'in_store,in_store_takeaway' } }), // phase 3S
client.get('/api/products/categories'),
])
const products = prodRes.data
const categories = catRes.data
db.products.bulkPut(products).catch(() => {})
db.categories.bulkPut(categories).catch(() => {})
warmPhotos(products, categories) // kept for offline (5.2)
return { products, categories }
}
async function loadFromCache() {
const [products, categories] = await Promise.all([
db.products.toArray(),
db.categories.toArray(),
])
if (products.length === 0 && categories.length === 0) return null
return { products, categories }
}
export function useProductCache() {
const queryClient = useQueryClient()
const [idbData, setIdbData] = useState(null)
const [idbLoaded, setIdbLoaded] = useState(false)
// Load IDB data immediately on mount — this is the offline fallback
useEffect(() => {
loadFromCache().then(data => {
setIdbData(data)
setIdbLoaded(true)
// Seed the query cache so React Query uses it as starting data
if (data && !queryClient.getQueryData(PRODUCTS_KEY)) {
queryClient.setQueryData(PRODUCTS_KEY, data)
}
})
}, [queryClient])
const query = useQuery({
queryKey: PRODUCTS_KEY,
queryFn: fetchAndCacheProducts,
staleTime: 5 * 60 * 1000,
gcTime: 60 * 60 * 1000,
// Don't retry on failure — axios interceptor already fired backend-offline
// which switches connection state; we fall back to IDB data instead
retry: false,
// Only start the query after we've checked IDB, so IDB data is visible first
enabled: idbLoaded,
})
// Prefer live query data; fall back to IDB snapshot if query failed or is loading
const data = query.data ?? idbData
return {
products: data?.products ?? [],
categories: data?.categories ?? [],
isLoading: !idbLoaded && query.isLoading,
}
}
export function invalidateProductCache(queryClient) {
queryClient.invalidateQueries({ queryKey: PRODUCTS_KEY })
}