next.js/packages/next/src/next-devtools/dev-overlay/hooks/use-active-runtime-error.ts
use-active-runtime-error.ts57 lines1.4 KB
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,
    }
  }

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

  return {
    isLoading,
    activeIdx,
    setActiveIndex,
    activeError,
    errorDetails,
    errorCode,
    errorType,
  }
}
Quest for Codev2.0.0
/
SIGN IN