Skip to content

Commit

Permalink
Optimise real-time compilation
Browse files Browse the repository at this point in the history
  • Loading branch information
csansoon committed Oct 10, 2024
1 parent a1125cf commit 5d8e061
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions apps/web/src/hooks/useMetadata.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
'use client'

import { DependencyList, useEffect, useState } from 'react'
import { useEffect, useState } from 'react'

import { ConversationMetadata, readMetadata } from '@latitude-data/compiler'
import { useDebouncedCallback } from 'use-debounce'

type Props = Parameters<typeof readMetadata>[0]
export function useMetadata(props: Props, deps: DependencyList) {
const [isLoading, setIsLoading] = useState(true)
export function useMetadata(props: Props) {
const [propsQueue, setPropsQueue] = useState<Props | null>(props)

useEffect(() => {
setPropsQueue(props)
}, Object.values(props))

const [isLoading, setIsLoading] = useState(false)
const [metadata, setMetadata] = useState<ConversationMetadata>()

const runReadMetadata = useDebouncedCallback(
(props: Props, onSuccess: (data: ConversationMetadata) => void) => {
readMetadata(props).then(onSuccess)
},
500,
{ trailing: true },
)

useEffect(() => {
if (isLoading) return
if (!propsQueue) return

setIsLoading(true)
readMetadata(props).then((m) => {
setPropsQueue(null)

runReadMetadata(propsQueue, (m) => {
setMetadata(m)
setIsLoading(false)
})
}, deps)
}, [isLoading, propsQueue])

return { metadata, isLoading }
}

0 comments on commit 5d8e061

Please sign in to comment.