Bootstrapping an Elm Project

Elm is a delightful language for building reliable web applications. It’s a language that gets compiled to JavaScript and so is used to build applications that run in a web browser.

In this post, we’re going to explore different ways of starting an Elm project, starting with the simplest and moving on to setups with more advanced features such as hot-reload in development.

Let’s get started!

Prerequisites

Before we get started, please make sure to Install Elm

To confirm if you have Elm installed, you can try running the interactive repl using the elm repl command. If you get a prompt such as the one shown in this image, you’re good to go 👍

Elm repl

Elm CLI

This is the officially supported way of creating a new Elm project.

  1. Create a new directory where your project will live

    mkdir my-awesome-elm-project

  2. Navigate to the newly created directory

    cd my-awesome-elm-project

  3. Run elm init inside this directory and you should get a prompt like the one below:

Elm init prompt

  1. Press the Enter key and it should create an elm.json file in the current directory. A src directory will also be created.

It is a good idea to read through the linked resource that talks more about starting new Elm projects

  1. Let’s start by creating a new Main.elm file in the src directory. Once we’ve created the file, let’s add some Elm code that should show us the classic "Hello World!" message once we run it.
module Main exposing (main)

import Browser
import Html exposing (h1, text)

main =
  h1 [] [ text "Hello World!" ]
  1. To run the code, let’s run elm reactor in our directory and it should start a new local server at http://localhost:8000. elm reactor is the simplest way to get started running Elm code.

  2. Once you navigate to http://localhost:8000, you should see an interface like the following.

Elm Reactor

Click on the src link, then Main.elm and you should be greeted by our "Hello World!" message.

And that’s it! We’ve successfully created a project the elm init command and run it using elm reactor.

Pros:

  • Easy to get started
  • No external dependencies apart from elm itself

Cons:

  • Manual reloading once we make changes

Elm Make

This is an extension of elm reactor and includes the ability to compile our Elm code to static HTML.

Using the same project from our previous section, we can compile the project using the command:

elm make src/Main.elm

Once we run this command, an index.html file will be generated in the current working directory, and if you open it in a web browser, you should see the same "Hello World" message.

I don’t have lots of experience with elm make so that’s as far as I’ll go with it.

Parcel

Parcel is a "Blazing fast, zero configuration web application bundler" and is my personal favourite to get started with an Elm application quickly. It handles compiling your Elm code to JavaScript and is super easy to get started with.

You can create an Elm application compiled by Parcel in a few simple steps:

  1. Install Parcel

    yarn global add parcel-bundler or npm install -g parcel-bundler

  2. Follow the instructions in the Elm section of the Parcel website, which involves:

  • creating an index.html file with the following contents:
  • creating an index.js file with the following contents:
import { Elm } from './Main.elm'

Elm.Main.init({
  node: document.querySelector('main')
})
  • creating a Main.elm file with the following contents:
module Main exposing (main)

import Browser
import Html exposing (h1, text)

main =
  h1 [] [ text "Hello, from Parcel!" ]
  1. To run the application, run the command: parcel index.html

I love this setup so much that I’ve created my own starter project based on Parcel. Feel free to check it out on GitHub

Pros:

  • Easy to get started with
  • No manual configuration needed 💪
  • Hot reload included out of the box
  • Easy to get started with JavaScript Interop

Cons:

🤷‍♀️

Notable Mentions:

This is not meant to be a comprehensive list, and any suggestions/additions are welcome in the comments section below.

I hope these options are useful for you when starting out your next Elm project 🚀

Cleaner Clojure Functions with the :pre Special Form

In the course of programming, it’s fairly common to face a scenario where you want to ensure that a function’s arguments fulfil some condition(s), and if not, to throw an error. In this post, we’re going to see how Clojure provides a handy special form that greatly simplifies this task.

One such scenario that I’ve come across recently is trying to come up with a function that would compute the 3x + 1 problem (Collatz conjecture). The problem is as follows:

Take any positive integer n.

If n is even, divide n by 2 to get n / 2.

If n is odd, multiply n by 3 and add 1 to get 3n + 1.

Repeat the process indefinitely.

The conjecture states that no matter which number you start with, you will always reach 1 eventually.

The task at hand was to write a function that takes a number as an argument and returns the number of steps it takes for the number to eventually be 1.

You’ll also notice that the first condition for the number to be passed in is that it has to be a positive integer. Therefore, given any value less than 1, the function should throw an error.

A typical solution in Clojure would look as follows:

collatz-first
Collatz first try

While this definitely works, I found out that Clojure provides a much more elegant way to accomplish this, with the help of the :pre special form.

This form enables specifying conditions about the arguments that should be met before the rest of the function body is evaluated. If any of the conditions is not met, an assertion error is thrown.

This is how we could rewrite the function making use of the :pre condition:

collatz-with-pre
Collatz with :pre special form

In this case, if the function is called with 0 or a negative number, an assertion error is automatically thrown.

I think you would agree that the second version looks much nicer 🙂

Auto-formatting your JavaScript Codebase with Prettier

While creating new JavaScript projects, I’ve found that I need to add Prettier to each one of them. Prettier is an awesome opinionated code formatter, with good enough defaults that I almost never need to configure it. It just works, and it looks good 🎨

I’m documenting this so that I can have a single place to refer to the next time. I’m also doing it because I honestly need to get back to producing content and I might as well start with something I find useful.

Also it’s 2018 and you want to spend your time actually writing code not thinking about whether to use double or single quotes every single time 😅

After initialising your project and ensuring you have a package.json file, run the following command to install prettier:

carbon

That’s enough to use prettier. It comes with nice defaults that work pretty well for most cases. However, if you must make changes to the config, here’s the different Prettier config options.

The next part is configuring Prettier to work with Visual Studio Code, my preferred editor.

In Visual Studio Code, go to the extensions pane and search for Prettier - Code formatter​ and install the first extension in the search results.

Now you can format the particular file by using the formatting key combination. Mine is control + option + b and this formats the file.

Prettier has support for lots of files, but I mostly use it for JavaScript, JSX, JSON, HTML and CSS as those are the ones I work with regularly.

And that ends today’s post. Hope you get to try out Prettier too, trust me, it’s awesome.

Getting Started Contributing to Nextcloud

In August 2018,  I had the pleasure of speaking at the Nextcloud Conference held at the Technical University Berlin. It was my first time giving a talk at a conference and I gave a lightning talk (5 minutes) about getting started contributing to Nextcloud. This is a blog post version of the talk I gave and hopefully it motivates you to get started contributing too!

What is Nextcloud?

Nextcloud is a set of technologies that enables file sharing and collaboration. I like to think of it as a self-hosted version of Google Drive or Dropbox. It enables its users to self-host and manage their files on their own servers, and offers lots of collaboration options. It also has apps that add more functionality such as calendar and email management, chat and video conferencing. A great place to learn more about the company is the Nextcloud website.

An interesting thing is that the software that powers all of this is entirely open source. Anyone can contribute to it, and this is where I come in. Contributing to open source software has always been one of my best learning avenues, and so I wanted to help others to get started contributing as well. I started contributing code to Nextcloud around 2 months ago and found that it’s a very welcoming community of people that would benefit from having even more contributors joining in.

Now that we know what Nextcloud is and why you would want to join as a contributor, let’s get to the actual process!

Building Trust

The core idea I follow when contributing to open source is building trust between myself as a developer and the maintainers of the software. Beyond just contributing code, I find that maintainers appreciate developers who help make their job easier. This involves things like working on the right stuff and proactive communication. This eventually leads to a build-up of trust over time and this process of earning this trust is what I will focus on in this post. I will go over it using practical examples from my experiences contributing to Nextcloud.

First Steps

Nextcloud has a good first issues label on their issue tracker to identify issues that are best suited for first time contributors. In my experience, this is the best place to get started if you’re contributing for the first time. At the time of writing this, there are 76 issues with this label so there’s lots of opportunities to contribute 😀

As a contributor, working on good first issues has quite some advantages:

  • You’re able to set up and run the project on your dev environment
  • You get familiar with the contribution process. This info is usually contained in a contributing doc on the repository
  • You start to gain the trust of the maintainers, since they see that you care enough to want to contribute

For the maintainers, a new contributor is able to help them in the following ways:

  • An issue actually gets fixed. It might be a simple problem to fix, but it’s still an impactful issue that makes the project better.
  • Identify potential friction points for new contributors e.g. if the contribution docs are unclear, if there’s missing docs, etc.
  • Building community. A good first contribution experience helps new contributors grow into more active community members and become potential future maintainers.

Use the Software

At this point, you’re a new contributor who has worked on a good first issue and hopefully got your contribution merged. To continue finding new opportunities to contribute, you have to actively use the software to get a feel of an end-user’s perspective. For example, once I got started using Nextcloud, I noticed it could have better support for keyboard navigation. I reported the issues I found on GitHub and eventually contributed fixes for them.

Once again, this has some benefits for you as the contributor, such as:

  • Learning how to file a helpful bug report e.g. what info to include to help reproduce an issue.
  • It enables more interaction with the maintainers i.e. you ask questions when stuck and they give you feedback on your contributions.
  • It helps build trust. Working through issues together is one of the best avenues to build trust between contributors and maintainers.

For the maintainers, when you use the software, report issues and fix them, it benefits them by:

  • Making it easier for them to provide help and guidance when you’re stuck
  • Helping set expectations on how to approach issues e.g. this comment shows a practical example of this point
  • Getting a perspective on what matters to different users

Explore the ecosystem

Most open source software projects usually have an ecosystem around them. In our case, Nextcloud has the concept of apps through which developers can add new functionalities beyond the main purpose of file-sharing and collaboration. Additionally, the officially supported Nextcloud apps are also open source too.

The apps offer a new place to build out a new set of skills by working on more diverse things. I chose to contribute to the Mail app which is an e-mail client built inside Nextcloud.

The advantages of working on the apps in the ecosystem are:

  • Smaller surface area. The apps usually have a very specific focus and consequently you can have more of an impact
  • There’s lots of apps and so there’s lots of opportunities to share best practices with the other apps e.g. There’s an effort to rewrite the mail app in Vue and we’ve taken lots of cues from the contacts app on the way to go about it.

Lessons Learnt

Having gone through all these steps above, and applied them while contributing to Nextcloud, here’s some of the things I’ve learnt:

  • The Nextcloud team is extremely welcoming to new contributors and very supportive in helping them grow. You should join to see for yourself 😃
  • Working with a fully open source team like Nextcloud is a great experience and I guarantee that you’ll learn a lot
  • Assume good intentions. Be nice when interacting with others online.
  • Take ownership of issues you pick up. Take the work seriously and take it to completion. Again, this helps build trust.
  • Things are not always perfect e.g. your contributions may take some time to be reviewed/merged, etc. Be patient and remember to be nice.

If you’ve ever wanted to get started contributing to open source, and not sure on how to get started, I hope these pointers help. Everyone started somewhere.

Finally, I’d love to give a shout-out the Nextcloud team for their Contributor Travel Support Program, which enabled me to attend the conference this year 😀

Update:

The video of the talk is now available. You can watch it below

Posting Source Code on WordPress

Posting Source Code on WordPress

While writing technical content for this blog, I usually find it tough to include source code in the posts in a way that makes it readable and appealing. I want it to be enjoyable to read the code, rather than a struggle.

This led me to explore various solutions and in this post I go over the options I considered and what I eventually found to work best for me.

In my search, I considered the following 3 options:

Gist Embed

This is where I post the source code on gist.github.com and then embed the gist in the blog post.

Pros:

  • Gist embedding is natively supported in WordPress
  • Amazing out of the box syntax highlighting
  • Simple for the reader to copy the code directly from the post if they need to

Cons:

  • Content not rendered on some platforms e.g. In the Pocket mobile app and in the AMP version of the site

This is how a Gist embed looks:

WordPress Source Code Embed

This works through using some special tags directly in the post, and any text you put between these tags, is then interpreted as code and gets syntax-highlighted. More details on this on this WordPress Support page.

Pros:

  • Extremely simple to insert code right in the editor as the post author
  • Simple for the reader to copy the code directly from the post
  • Natively supported in WordPress

Cons:

  • Not the best syntax highlighting option
  • Limited languages supported

I wasn’t able to properly embed the JSX code snippet above using this option without trying to pull my hair out, so to see how this option looks, I suggest you check it out in my previous post: A Practical Use Case for React’s componentDidUpdate

carbon.now.sh

This is a relatively new option and one that I’m excited to try out.

There’s an awesome website carbon.now.sh that claims to help you create and share beautiful images of your source code, and it definitely fulfills this bold claim. All you have to do is post your code on the website and it generates a beautiful image of the source code that you can embed anywhere, including on a blog post.

Pros:

  • Truly beautiful images 😍
  • Awesome syntax highlighting, almost exactly what you would get in your editor
  • A variety of themes to choose from
  • Directly import source code from GitHub gist (carbon.now.sh/GIST_ID_HERE)

Cons:

  • Generates images, so it’s not possible to copy the source code from the post

This is how this ends up looking on a post:

carbon_2018-08-11_14-20-13

Conclusion

Afer evaluating all these options, I found that what works best for me is a combination of gist.github.com and carbon.now.sh

My workflow now involves posting the code in GitHub Gist and using the Gist ID to generate an image on Carbon. In the actual post, I then embed the Carbon generated image and add a link to the gist. This way I can take advantage of both these awesome services.

To see all of these options in a practical post, you can check out my previous post: A Practical Use Case for React’s componentDidUpdate

A Practical Use Case for React’s componentDidUpdate

A Practical Use Case for React’s componentDidUpdate

Working with React and JavaScript is always fun because it’s always a chance to learn something new. Today we’ll visit one such case I came across recently that helped me learn more about when to use componentDidUpdate in React. Let’s dive in!

Scenario

Let’s take a scenario where we’re building a blog app. The blog will be very minimal, with these features:

  1. When a user visits the homepage, they should see a list of posts and should be able to click on any of the posts to be taken to the blog post’s page.
  2. When a user visits a blog post page, they should see the blog details i.e. title and content, and a list of recommended posts at the bottom of the page.
  3. Clicking on a recommended blog post’s link should take the user to that post’s page.

Now that we’ve figured out the requirements, let’s proceed to build the app.

Building the App

We will need 3 components for our app: the home page, the blog post component and the app’s root component, which decides which page to render depending on the route. For this example, we’ll fetch the posts from a local file rather than making network requests.

Let’s start off with the root component, which is where we’ll mount the app to a specific DOM node.

We’re using the ​​react-router-dom package to render either the Home or PostDetails component depending on the route. A request with a URL such as /posts/2 will be routed to the PostDetails component and the postId variable will take the value of 2.

Let’s look at the Home component, which will act as our homepage:

In this file, we fetch posts locally from posts.js and use  the Home component render a list of links to each of the posts. Each post has an id attribute which is used to construct the URL using the Link helper from react-router-dom​

This is how our sample ​post data looks:

The final piece of the puzzle is the ​​PostDetails.jsx component:

carbon_2018-08-11_14-20-13

Link to PostDetails.jsx

In this component, we’ll store the post’s details in the component state, and all the values are initially empty. To fetch the post’s data, we’ll need to extract the postId parameter from the URL. ​​​​​​​​​​​​​​react-router-dom stores the route params in the component’s props and it enables us to access this parameter via this.props.match.params.postId. Once we have the postId, we then find the post with a matching ID in the posts array, and set it in the component state. This is handled in thefetchPostData function.

In the ​​render method, we show the post’s details and a Recommeded Posts section. When you click on one of the posts in this section, you should be taken to that post’s URL and shown that post’s details.

You can try out the app in it’s current state at CodeSandbox and also view the live code in the Live Editor

However, we have a bug lurking somewhere in our code. Try clicking on one of the recommended posts and see what happens.

Figuring out the Problem

If you haven’t tried out the live app, the issue we have is that when we’re in a blog post’s page, clicking on a recommended post doesn’t seem to do anything. If you’re keen though, you’ll notice that the URL does change but the page content doesn’t change 🤔

When you click on a recommended blog post link, React Router re-renders the PostDetails route component with a new postIdparameter. This parameter is passed to the component as props. We can be sure the component does receive new props since the URL changes. But why does the component fail to display the updated data?

The root of the issue here is that we fetch data only on componentDidMount which is not called when a component re-renders.

What we need to do to solve the problem is to fetch new post data when we detect that the postId parameter has changed. This is where componentDidUpdate comes in.

Solution

Here’s a comment I came across in the react-router issue tracker that let me down the right path.

You probably want to just respond to prop changes with componentDidUpdate to refetch data when the same route is active but with different parameters

Ryan Florence

Therefore, to fix the issue, we have to add componentDidUpdate, where we’ll check if the postId has been updated and then fetch the details of the new post. Once we have the new details and store them in the component state, the component re-renders and shows the updated content.

Here’s the small addition we need to make to fix the bug (L18-28):

The componentDidUpdate lifecycle method takes in the previous props as the first argument. We extract the postId from the previous props, and compare that with the postId from the current props. If there’s a change, we fetch new data using the current postId parameter. This helps us update the page content when the component re-renders with a new postId parameter, and this fixes our bug!

You can try out the new bug-free version on CodeSandbox and check out the code on the Live Editor. If you’re interested in the accompanying code samples, you can access them on GitHub.

And thus ends the story of how I learned how to use componentDidUpdate on a real practical problem. This was an interesting discovery for me and I hope you’ve learnt something new too!

Featured Photo  (CC BY 2.0) courtesy of Malin Bobeck 

How to Introduce Elm to a React Codebase

How to Introduce Elm to a React Codebase

Elm is a delightful language that helps make web applications more reliable by eliminating runtime exceptions. I find it extremely productive working with Elm, and would like to be able to use it in a JavaScript codebase without breaking the existing application or having to rewrite it altogether. However, it’s not obvious how to try out Elm in a small piece of the application, just enough to evaluate how well it works. This is what we will address in this article by exploring how to add a new feature to a React codebase with Elm.

Continue reading “How to Introduce Elm to a React Codebase”