Skip to content

Commit

Permalink
fix(hooks): useFont hook loading state lifecycle is now accurate
Browse files Browse the repository at this point in the history
  • Loading branch information
heyitsarpit committed Dec 25, 2021
1 parent 55f4c4d commit dd08873
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions packages/core/useFont/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { useState } from 'react'

import { useMount } from '../useMount'
import { useEffect, useState } from 'react'

/**
* React FontFace, a hook to load fonts asynchronously
Expand All @@ -16,23 +14,22 @@ export function useFont(
source: string | Blob,
descriptors?: FontFaceDescriptors
) {
const [loaded, setLoaded] = useState(false)
const [loaded, setLoaded] = useState(true)
const [error, setError] = useState(false)
const [font, setFont] = useState<FontFace | null>(null)

useMount(() => {
useEffect(() => {
const font = new FontFace(family, `url(${source})`, descriptors)

setFont(font)
setLoaded(false)

font
.load()
.then(() => {
document.fonts.add(font)
setLoaded(true)
})
.then(() => document.fonts.add(font))
.catch(() => setError(true))
})
.finally(() => setLoaded(true))
}, [descriptors, family, source])

return { loaded, error, font }
}

0 comments on commit dd08873

Please sign in to comment.