Skip to content

Commit

Permalink
fix(apps/frontend-pwa): make sure that practice quiz does not rerende…
Browse files Browse the repository at this point in the history
…r every second due to time tracking (#4266)
  • Loading branch information
sjschlapbach authored Sep 19, 2024
1 parent 40c2f45 commit 533be1b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { useEffect, useState } from 'react'
import { MutableRefObject, useEffect, useState } from 'react'

function useComponentVisibleCounter() {
function useComponentVisibleCounter({
timeRef,
}: {
timeRef: MutableRefObject<number>
}) {
const [inFocus, setInFocus] = useState(true)
const [timeSpent, setTimeSpent] = useState(0)

// update time spent on stack if the stack is visible
useEffect(() => {
const timer = setInterval(() => {
if (inFocus) {
setTimeSpent((current) => current + 1)
timeRef.current = timeRef.current + 1
} else {
clearInterval(timer)
}
Expand All @@ -17,7 +20,7 @@ function useComponentVisibleCounter() {
return () => {
clearInterval(timer)
}
}, [inFocus])
}, [inFocus, timeRef])

// track if the current tab is in focus or not
useEffect(() => {
Expand All @@ -30,8 +33,6 @@ function useComponentVisibleCounter() {
window.removeEventListener('focus', handleFocus)
}
}, [])

return timeSpent
}

export default useComponentVisibleCounter
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import useStudentResponse from '@klicker-uzh/shared-components/src/hooks/useStud
import { useLocalStorage } from '@uidotdev/usehooks'
import { Button, H2 } from '@uzh-bf/design-system'
import { useTranslations } from 'next-intl'
import { useMemo, useState } from 'react'
import { useMemo, useRef, useState } from 'react'
import useComponentVisibleCounter from '../hooks/useComponentVisibleCounter'
import useStackElementFeedbacks from '../hooks/useStackElementFeedbacks'
import Bookmark from './Bookmark'
Expand Down Expand Up @@ -55,7 +55,8 @@ function ElementStack({
hideBookmark = false,
}: ElementStackProps) {
const t = useTranslations()
const timeSpent = useComponentVisibleCounter()
const timeRef = useRef(0)
useComponentVisibleCounter({ timeRef })

const [respondToElementStack] = useMutation(RespondToElementStackDocument)
const elementFeedbacks = useStackElementFeedbacks({
Expand Down Expand Up @@ -222,7 +223,7 @@ function ElementStack({
variables: {
stackId: stack.id,
courseId: courseId,
stackAnswerTime: timeSpent,
stackAnswerTime: timeRef.current,
responses: Object.entries(studentResponse).map(
([instanceId, value]) => {
if (value.type === ElementType.Flashcard) {
Expand Down

0 comments on commit 533be1b

Please sign in to comment.