ReactErrorBoundary
Robust error boundary library for Lua React based on react-error-boundary. See ErrorBoundary for the main component usage.
Types
ErrorBoundaryContextType
interface
ErrorBoundaryContextType {
didCatch:
boolean
error:
any
resetErrorBoundary:
(
...any
)
→
(
)
}
FallbackProps
interface
FallbackProps {
error:
Error
resetErrorBoundary:
(
...any
)
→
(
)
--
Resets the error boundary and calls onReset
if provided. This is useful for reverting state or retrying the render.
}
Props for fallback components. Fallback components should be typed like:
local Fallback: React.FC<ReactErrorBoundary.FallbackProps> = function(props)
-- ...
end
Functions
withErrorBoundary
ReactErrorBoundary.
withErrorBoundary
(
component:
React.ComponentType
<
Props
>
,
errorBoundaryProps:
types.ErrorBoundaryProps
) →
(
)
This is a higher-order component that makes it easy to add an error boundary to an existing component. See ErrorIn1SecondHOC for a full example.
note
If using luau strict mode, the component must be typed using local Component: React.FC<{ <prop-types> }> = function(props)
for types to work.
useErrorBoundary
ReactErrorBoundary.
useErrorBoundary
(
) →
UseErrorBoundaryApi
<
E
>
Types
interface
UseErrorBoundaryApi<E> {
resetBoundary:
(
)
→
(
)
showBoundary:
(
error:
E
)
→
(
)
}
Convenient hook for imperatively invoking or resetting error boundaries.
Invoking the nearest error boundary from an event handler
React only handles errors thrown during render or during component lifecycle methods (e.g., useEffect, componentDidMount). Error thrown in event handlers or in separate lua threads will not be automatically caught.
A convenient pattern is to invoke the nearest error boundary when an error occurs in event handlers or in separate lua threads.
local Example: React.FC<{}> = function()
local errorBoundary = useErrorBoundary()
useEffect(function()
-- Using promises
fetchPlayerData(name):andThen(function(res)
-- Set data in state to rerender
end):catch(function(error)
-- Our promise failed, so invoke the nearest error boundary to handle the error
errorBoundary.showBoundary(error)
end)
-- Using pcall
task.defer(function()
local success, res = pcall(function()
-- Do something that might throw an error
end)
if not success then
errorBoundary.showBoundary(res)
end
end)
end)
-- Render ...
end
Resetting the nearest error boundary
resetBoundary()
requests the nearest boundary to retry the render that originally failed and if passed,
invokes the boundary's onReset
callback.
A pattern is to just retry the render blindly and hope it succeeds on the second try. See RetryError for a full example.
A more common pattern is to revert some state and retry the render with the reverted state. See ResetCount for a full example.