11import { create } from 'zustand'
22
33interface PremiumQueryCountState {
4- count : number
4+ count : number | null
55 isUnlimited : boolean
66 set : ( count : number , isUnlimited : boolean ) => void
77 decrement : ( ) => void
88 reset : ( ) => void
9+ syncFromDb : ( count : number , isUnlimited : boolean ) => void
910}
1011
11- export const usePremiumQueryCountStore = create < PremiumQueryCountState > ( ( set ) => ( {
12- count : 50 ,
13- isUnlimited : false ,
14- set : ( count , isUnlimited ) => set ( { count, isUnlimited } ) ,
15- decrement : ( ) => set ( ( s ) => s . isUnlimited ? s : { ...s , count : Math . max ( 0 , s . count - 1 ) } ) ,
16- reset : ( ) => set ( { count : 50 , isUnlimited : false } ) ,
17- } ) )
12+ function persist ( count : number | null , isUnlimited : boolean ) {
13+ if ( typeof window !== 'undefined' ) {
14+ if ( count !== null ) localStorage . setItem ( 'premiumQueryCount' , String ( count ) )
15+ localStorage . setItem ( 'isUnlimited' , String ( isUnlimited ) )
16+ }
17+ }
18+
19+ export const usePremiumQueryCountStore = create < PremiumQueryCountState > ( ( set , get ) => {
20+ // Hydrate from localStorage
21+ let count : number | null = 50
22+ let isUnlimited = false
23+ if ( typeof window !== 'undefined' ) {
24+ const stored = localStorage . getItem ( 'premiumQueryCount' )
25+ const unlimited = localStorage . getItem ( 'isUnlimited' )
26+ if ( stored ) count = Number ( stored )
27+ if ( unlimited ) isUnlimited = unlimited === 'true'
28+ }
29+ return {
30+ count,
31+ isUnlimited,
32+ set : ( count , isUnlimited ) => {
33+ persist ( count , isUnlimited )
34+ set ( { count, isUnlimited } )
35+ } ,
36+ decrement : ( ) => {
37+ const { count, isUnlimited } = get ( )
38+ if ( ! isUnlimited && count !== null ) {
39+ const newCount = Math . max ( 0 , count - 1 )
40+ persist ( newCount , isUnlimited )
41+ set ( { count : newCount } )
42+ }
43+ } ,
44+ reset : ( ) => {
45+ persist ( 50 , false )
46+ set ( { count : 50 , isUnlimited : false } )
47+ } ,
48+ syncFromDb : ( count , isUnlimited ) => {
49+ persist ( count , isUnlimited )
50+ set ( { count, isUnlimited } )
51+ } ,
52+ }
53+ } )
0 commit comments