Document using getDerivedStateFromError with error boundaries

This commit is contained in:
Juho Teperi 2019-10-02 12:59:00 +03:00
parent 54834246f2
commit edb3d2d322
2 changed files with 35 additions and 9 deletions

View File

@ -49,19 +49,43 @@ Tests contain example of using old React lifecycle Context API (`context-wrapper
## [Error boundaries](https://reactjs.org/docs/error-boundaries.html) ## [Error boundaries](https://reactjs.org/docs/error-boundaries.html)
You can use `ComponentDidCatch` lifecycle method with `create-class`: [Relevant method docs](https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror)
You can use `getDerivedStateFromError` (since React 16.6.0 and Reagent 0.9) and `ComponentDidCatch` lifecycle method with `create-class`:
```cljs
(defn error-boundary [comp]
(let [error (r/atom nil)]
(r/create-class
{:component-did-catch (fn [this e info]
(reset! error e))
:get-derived-state-from-error-test (fn [error] #js {})
:reagent-render (fn [comp]
(if @error
[:div
"Something went wrong."
[:button {:on-click #(reset! error nil)} "Try again"]]
comp))})))
```
Alternatively, one could use React state instead of RAtom to keep track of error state, which
can be more obvious with the new `getDerivedStateFromError` method:
```cljs ```cljs
(defn error-boundary [comp] (defn error-boundary [comp]
(r/create-class (r/create-class
{:component-did-catch (fn [this e info] {:constructor (fn [this props]
(reset! error e)) (set! (.-state this) #js {:error nil}))
:reagent-render (fn [comp] :component-did-catch (fn [this e info]
(if @error (js/console.error "Error inside error boundary" e))
[:div :get-derived-state-from-error-test (fn [error] #js {:error error})
"Something went wrong." :render (fn [this]
[:button {:on-click #(reset! error nil)} "Try again"]] (r/as-element
comp))})) (if @error
[:div
"Something went wrong."
[:button {:on-click #(.setState this #js {:error nil})} "Try again"]]
comp))})))
``` ```
## [Hooks](https://reactjs.org/docs/hooks-intro.html) ## [Hooks](https://reactjs.org/docs/hooks-intro.html)

View File

@ -1044,6 +1044,8 @@
(r/create-class (r/create-class
{:component-did-catch (fn [this e info] {:component-did-catch (fn [this e info]
(reset! error e)) (reset! error e))
:get-derived-state-from-error (fn [error]
#js {})
:reagent-render (fn [comp] :reagent-render (fn [comp]
(if @error (if @error
[:div "Something went wrong."] [:div "Something went wrong."]