Gå til forsiden

Slaying a UI antipattern with TypeScript and React (part 2)

This time we are folding data based on external data in a neat way.

By Creator: Jost Haller - Colmar : Saint Georges terrassant le dragon, Olivier from FRANCE

In my previous post, I promised to build on the RemoteData type based on the popular Elm pattern.

This time we will make the switch statement in the Main React component into a thing of beauty.

Use the code from the CodeSandbox from the previous post as a starter code.

This function pretty much just a less verbose version of the switch statement, but very practical.

This way of doing it makes sense because the pattern has a somewhat logical order.

Split the logic

Just because it’s good to separate stuff into smaller functions, we can start with extracting the views out of the Main.

Doing this makes the Main function already look very clean.

Writing the fold function

Let us dive in and make the utility function for RemoteData. It might look weird, but just type it out yourself, and I think it will make sense to you.

The function is heavily based on gcantis Flow port of RemoteData.

I made the fold function a bit more general. I also ditched it being curried as it disabled type inference on the data and error types.

What you see is a higher order function. Don’t be afraid. It just means a function that takes in or returns functions. You probably deal with it all the time.

Using the fold function

Now, you can replace the switch statement with the foldRemoteData function

Very sleek!

RemoteData Libraries

If you like this pattern, but you prefer to use a library, there are some alternatives:

The devexperts version seems to have some advanced utilities, but I wish there were any examples in the docs.

You can pretty easily make your own convenience functions as the pattern is really simple anyway.

I currently prefer to just put the RemoteData type and the fold function into my own code. That’s pretty much all I need, and there isn’t much more to it.

Next up

That's it for RemoteData, but there is yet another part to this series.

I want this code to mimic the advantages of Elm. That will require a few more steps.

In the next post we are decoding the incoming data.

Decoding JSON doesn't sound very cool, but it's one of those features in Elm that makes it almost impossible to get run-time exceptions in production.

And with a functional library based on TypeScript, it's pretty easy. Purify to the rescue!


Litt om forfatteren

Lars Lillo Ulvestad

Lars Lillo Ulvestad

Frontendutvikler med bakgrunn som kommunikasjonsrådgiver i Direktoratet for utviklingssamarbeid (Norad) og journalist i Teknisk Ukeblad.
comments powered by Disqus