So you’re working on a React app and you finally decide it’s time to venture off of the golden path and actually incorporate some error handling. You know — instead of console.log’ing out your errors. Which I totally don’t do. Hah hah.
But do you ever find yourself writing a ton of conditionals in your view? Maybe you store your error messages in the Redux store and display them like this:
This can get icky and repetitive really fast. In this contrived example, it doesn’t seem like that big of a deal. But I’m sure your views are more complex than 1 div and 1 heading. Imagine having to do something like this across multiple containers, across multiple screens, and so on.
Here’s a Codepen with a more fleshed out example where we conditionally show our error message:
Okay — so how can make this code sexier? We can use a higher order component to extract our conditional logic out of the view. Let’s do it:
2. Use HOC
Sweeet! I think this is much cleaner. These same concepts can be applied to rendering a
<Loading /> component when you are making an async call.
You can play with the HOC version here: