Skip to content

Commit

Permalink
Merge pull request #15 from purduehackers/use-layout-effect
Browse files Browse the repository at this point in the history
Ensure time values are populated before first render
  • Loading branch information
MatthewStanciu authored Nov 17, 2023
2 parents 14fbcb3 + 892b78f commit 512a340
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@purduehackers/time",
"version": "0.6.5",
"version": "0.6.6",
"description": "convert between traditional time and lightning time ⚡️",
"main": "dist/index.js",
"module": "dist/esm/index.js",
Expand Down
33 changes: 25 additions & 8 deletions src/react/index.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useRef, useLayoutEffect } from 'react'
import { format as formatTime } from 'date-fns'
import { LightningTime, MILLIS_PER_CHARGE } from '../time'
import { Colors } from '../types'

export function useLightningTimeClock() {
const [lightningTimeClock, setLightningTime] = useState<string>('0~0~0')
const [normalTimeClock, setNormalTime] = useState<string>('12:00 AM')
const [lightningTimeClock, setLightningTime] = useState<string>('')
const [normalTimeClock, setNormalTime] = useState<string>('')
const [timeColors, setTimeColors] = useState<Colors>({
boltColor: '#00000000',
zapColor: '#00000000',
sparkColor: '#00000000'
boltColor: '',
zapColor: '',
sparkColor: ''
})
const isFirstRender = useRef(true)

useLayoutEffect(() => {
if (isFirstRender.current) {
const now = new Date()
const { lightningString, colors } =
new LightningTime().convertToLightning(now)
const formattedTime = formatTime(now, 'h:mm a')

setLightningTime(lightningString)
setNormalTime(formattedTime)
setTimeColors(colors)

isFirstRender.current = false
}
}, [])

useEffect(() => {
const update = () => {
Expand All @@ -24,12 +40,13 @@ export function useLightningTimeClock() {

const lt = new LightningTime()
const convertedTime = lt.convertToLightning(now).lightningString
const formattedTime = formatTime(now, 'h:mm a')
const colors = lt.getColors(convertedTime)

setLightningTime(convertedTime)
setTimeColors(colors)

const formattedTime = formatTime(now, 'h:mm a')
setNormalTime(formattedTime)

setTimeout(update, remainingMillis)
}
update()
Expand Down

0 comments on commit 512a340

Please sign in to comment.