DEV Community

Stop Pretending The Error Never Happened! Be Explicit About Loading State

Rens Jaspers on February 27, 2024

We all need to stop using placeholder values that look like correctly resolved values in RxJS streams that error out! This is a pattern you see i...
Collapse
 
rensjaspers profile image
Rens Jaspers • Edited

Shoutout to @simonjaspers for suggesting the use of a union type for the loading state, instead of a single type with optional error and data properties.

This trick prevents you from creating nonsensical loading states. For example, the TypeScript compiler will helpfully throw an error if you try to create a state like { state: "loading", error: error }, as you can’t be in a loading and hold an error value at the same time.

The union type also makes writing templates easier, as TypeScript can figure out which variant of the union type is being referenced with each @switch(emails.state) case.

For @case("loading"), intellisense will tell you that the object won't have data or error properties, and for @case("loaded"), it understands that there will be data but there will be no error value. So trying to access {{emails.error.message}} in the template under @case("loaded") will throw a compilation error. :-)

Collapse
 
jangelodev profile image
João Angelo

Hi Rens Jaspers,
Your tips are very useful
Thanks for sharing

Collapse
 
rensjaspers profile image
Rens Jaspers

Hi João Angelo,

Thank you for your kind words! I'm glad you find my tips helpful. I'm curious about the projects you're working on. Maybe you'd like to try my *ngxLoadWith directive in your projects. I believe it can make your code simpler and improve the experience for your users when loading data. Let me know what you think!

Best,
Rens