From 8910599da4006b198a58b339b285b1b7b2d50585 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Sun, 5 Sep 2021 19:39:12 +0300 Subject: [PATCH] Add useError hook --- snippets/useError.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 snippets/useError.md diff --git a/snippets/useError.md b/snippets/useError.md new file mode 100644 index 000000000..4833eb685 --- /dev/null +++ b/snippets/useError.md @@ -0,0 +1,41 @@ +--- +title: useError +tags: hooks,state,effect,intermediate +firstSeen: 2021-09-30T05:00:00-04:00 +--- + +Creates an error dispatcher. + +- Use the `useState()` hook to create a state variable that holds the error. +- Use the `useEffect()` hook to `throw` the error whenever it's truthy. +- Use the `useCallback()` hook to update the state and return the cached function. + +```jsx +const useError = err => { + const [error, setError] = React.useState(err); + + React.useEffect(() => { + if (error) throw error; + }, [error]); + + const dispatchError = React.useCallback(err => { + setError(err); + }, []); + + return dispatchError; +}; +``` + +```jsx +Rconst ErrorButton = () => { + const dispatchError = useError(); + + const clickHandler = () => { + dispatchError(new Error('Error!')); + }; + + return ; +}; + +ReactDOM.render(, document.getElementById('root')); +```