File size: 1,796 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import type { ReadyRuntimeError } from '../utils/get-error-by-type'
import type { HydrationErrorState } from '../../shared/hydration-error'

import { useMemo, useState } from 'react'
import { getErrorTypeLabel, useErrorDetails } from '../container/errors'
import { extractNextErrorCode } from '../../../lib/error-telemetry-utils'

export function useActiveRuntimeError({
  runtimeErrors,
  getSquashedHydrationErrorDetails,
}: {
  runtimeErrors: ReadyRuntimeError[]
  getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
}) {
  const [activeIdx, setActiveIndex] = useState<number>(0)

  const isLoading = useMemo<boolean>(() => {
    return runtimeErrors.length === 0
  }, [runtimeErrors.length])

  const activeError = useMemo<ReadyRuntimeError | null>(
    () => runtimeErrors[activeIdx] ?? null,
    [activeIdx, runtimeErrors]
  )

  const errorDetails = useErrorDetails(
    activeError?.error,
    getSquashedHydrationErrorDetails
  )

  if (isLoading || !activeError) {
    return {
      isLoading,
      activeIdx,
      setActiveIndex,
      activeError: null,
      errorDetails: null,
      errorCode: null,
      errorType: null,
      notes: null,
      hydrationWarning: null,
    }
  }

  const error = activeError.error
  const errorCode = extractNextErrorCode(error)
  const errorType = getErrorTypeLabel(error, activeError.type)

  // TODO(GH#78140): May be better to always treat everything past the first blank line as notes
  // We're currently only special casing hydration error messages.
  const notes = errorDetails.notes
  const hydrationWarning = errorDetails.hydrationWarning

  return {
    isLoading,
    activeIdx,
    setActiveIndex,
    activeError,
    errorDetails,
    errorCode,
    errorType,
    notes,
    hydrationWarning,
  }
}