All Downloads are FREE. Search and download functionalities are using the official Maven repository.

core.error.Container.tsx Maven / Gradle / Ivy

The newest version!
import React, {
    createContext,
    useContext,
    useMemo,
    isValidElement,
} from 'react'

import {
    ErrorContainerProps,
    ErrorContainerContextType,
    ErrorContainerProviderProps,
    ErrorComponent,
} from './types'

const ErrorHandlersContext = createContext([])

export function ErrorHandlersProvider({ value, children }: ErrorContainerProviderProps) {
    const parentValue = useContext(ErrorHandlersContext)
    const mergedValue = useMemo(() => [...value, ...parentValue], [parentValue, value])

    return (
        
            {children}
        
    )
}

export function ErrorContainer({
    error,
    onReset,
    children,
}: ErrorContainerProps) {
    const handlers = useContext(ErrorHandlersContext)

    const errorComponent = useMemo(() => {
        if (!error) { return null }

        for (const handler of handlers) {
            const result = handler(error)

            if (result && isValidElement(result)) {
                return result
            }

            if (typeof result === 'function') {
                const Component = result as ErrorComponent

                return 
            }
        }

        return <>{error.toString()}
    }, [error, handlers, onReset])

    if (!errorComponent) { return children }

    return (
        
{errorComponent}
) } ErrorContainer.defaultProps = { onReset() { // ignore }, } ErrorContainer.displayName = 'ErrorContainer'




© 2015 - 2024 Weber Informatics LLC | Privacy Policy