Skip to content

Commit

Permalink
feat(useTitle): support gettable title in SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
vikiboss committed Jun 21, 2024
1 parent 43d961a commit 16c9d5a
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/use-title/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useCreation } from '@shined/react-use'
import { useDeepCompareEffect } from '../use-deep-compare-effect'
import { useGetterRef } from '../use-getter-ref'
import { useLatest } from '../use-latest'
import { useMount } from '../use-mount'
import { useStableFn } from '../use-stable-fn'
import { useUnmount } from '../use-unmount'
import { isFunction } from '../utils/basic'
import { unwrapGettable } from '../utils/unwrap'

import type { Gettable } from '../utils/basic'

/**
* `%s` will be replaced by the title if the template is a `string`
Expand All @@ -27,19 +29,20 @@ export type UseTitleOptions = {
template?: UseTitleTemplate
}

export function useTitle(newTitle: string, options: UseTitleOptions = {}) {
export function useTitle(newTitle: Gettable<string>, options: UseTitleOptions = {}) {
const [originalTitleRef, originalTitle] = useGetterRef('')
const { template = '%s', restoreOnUnmount = false } = options

const latest = useLatest({ template, restoreOnUnmount })
const nextTitle = unwrapGettable(newTitle)

useMount(() => {
originalTitleRef.current = document.title
})

useDeepCompareEffect(() => {
document.title = format(newTitle, latest.current.template)
}, [newTitle])
document.title = format(nextTitle, latest.current.template)
}, [nextTitle])

const restore = useStableFn(() => {
document.title = originalTitle()
Expand Down

0 comments on commit 16c9d5a

Please sign in to comment.