When Flow typing didn’t quite work properly (and it was all my own fault)

I’m working on a Javascript and React application, which uses Flow to enforce types. For the most part, I love working with Flow, but it hadn’t been working properly for a while.

My IDEs (both Webstorm and VSCode) both reported type errors correctly, but running flow check at the command line (or on CircleCI) always returned No errors! Great, except there were errors lurking in there – loads more than Webstorm was finding!

It turned out to be because I had this line in my .flowconfig:

[options]
module.system.node.resolve_dirname=src

That was there so I could use absolute imports (meaning I could type import Foo from "utils/bar"; instead of import Foo from "../../../../../../../../utils/bar";). Unfortunately that turned out to a broken config, which masked a hell of a lot of problems! Luckily I wasn’t the first person to run into this. The correct way to do that is:

[options]
module.name_mapper='^utils/\(.*\)$' -> '<PROJECT_ROOT>/src/utils/\1'

And add another module.name_mapper line for each top-level folder under src.

If you’re importing from a file at the top level (e.g. import type { Foo } from "flow-types";) the module.name_mapper will look something like this:

module.name_mapper='^flow-types' -> '<PROJECT_ROOT>/src/flow-types.js'

Unfortunately, when I corrected the problem, it revealed a lot of Flow errors in my codebase. Flow has got a lot more strict since I introduced the problem (and that’s a good thing). Luckily, most of those issues are relatively simple to fix!

What to do when the HTML download attribute is ignored

It turns out web browsers will usually ignore the <a download="filename"> HTML attribute on cross-origin requests.

The answer is for the server to set the HTTP Content-Disposition header in the response:

Content-Disposition: attachment;

This assumes the filename on the server is correct. In my case (for complicated and boring reasons), it is not, so I also need to set a filename in in the Content-Disposition HTTP header, e.g. Content-Disposition: attachment; filename="example.pdf".

In my case, the files are stored on a Google Storage bucket. Their name is not the same as the name the user wants (e.g. the file is called export_yVW4Bg-f63rpZIUiXvWct.pdf but the user wants export_31Jan2022.pdf). So when I create the file, I also need to set the Content-Disposition header accordingly.

This code snippet is part of a Google Cloud Function running on NodeJS, and I’m using the @google-cloud/storage library:

const { Storage } = require("@google-cloud/storage");

// Set the metadata to make the PDF download correctly
const setFileMetadata = async (
  bucketName,
  fileName,
  downloadFileName
) => await storage
      .bucket(bucketName)
      .file(fileName)
      .setMetadata({
        contentDisposition: `attachment; filename="${downloadFileName}"`,
        contentType: contentType,
      });

await setFileMetadata("my-unique-bucket-name", "export_yVW4Bg-f63rpZIUiXvWct.pdf", "export_31Jan2022.pdf");

Google’s engineers have posted a more comprehensive code sample, showing how you can also set other headers (e.g. cache-control) and metadata on the file.

The 1996 GT LTS-3

I had one of those, in black! It was rad. Also terrible and squeaky. But mostly rad.

HTML forms with multiple buttons

Lets say you have an HTML form with multiple buttons. One button submits the form, but the others do something else. Here’s a simple example:

<form>
  <label>
    Email address
    <input type="email" name="email" />
  </label>
  <button onClick="handleCancel()">Cancel</button>
  <button>Save</button>
</form>

I might type my email address into the form, press Enter, and… oops. For some reason, pressing Enter chooses the Cancel button.

The fix is to add type="button" to any button which should not submit the form, and type="submit" to any buttons which should submit the form, like so:

<form>
  <label>
    Email address
    <input type="email" name="email" />
  </label>
  <button type="button" onClick="handleCancel()">Cancel</button>
  <button type="submit">Save</button>
</form>

Pressing Enter will now submit the form, as expected.

Electric milk floats

When I was a kid, we had milk delivered to our door every day. There’s plenty to be said about that, but today’s point: It was delivered by an EV, and at the time it was completely normal.

When I was growing up in the 1980s, we had fresh milk delivered to our door every day, by someone driving an EV. At the time that was completely normal. Over time, those EVs just faded away.

The EV design was chosen in part because they’re quiet (especially compared the the diesel and petrol engines of the time) – the milk was being delivered to residential streets in the early hours of the morning.

Unigate Milk Float
Unigate Milk Float by f1jherbert on Flickr.

There’s a lot of buzz around the likes of Amazon and UPS ordering huge numbers of EV delivery vehicles from companies like Rivian and Arrival. These things are super cool and potentially transformative, but the concept isn’t exactly new. Specialist electric vehicles designed for short hop (or last mile) deliveries in towns and cities have existed for nearly a century. It turns out Wales and Edwards started making these things in the early 1950s, and Morrison-Electricar were building them as far back as the 1930s.

We just forgot about them for a while.

Using Flow types with Reach Router route components

I have a project which uses Flow for static typing, and Reach Router for routing. Reach Router uses Route components to assign components to URLs:

<Router>
  <Component path="/somewhere" />
  <AnotherComponent path="/somewhere-else" />
  <YetAnotherComponent default />
</Router>

So if you browse to /somewhere-else, <AnotherComponent /> will be rendered. So far, so good. However, if one of these components doesn’t accept any props, Flow will complain:

export const AnotherComponent = () => {
  return <>I am another component.</>;
};

Error:(116, 10) Cannot create AnotherComponent element because property path is missing in function type [1] but exists in props [2].

To work around that, I created a Route component and a DefaultRoute component:

// @flow

import type { DefaultRouteProps, RouteProps } from "@reach/router";
import * as React from "react";

type RouteComponentProps = RouteProps & {
  component: React$ComponentType<*>,
};

type DefaultRouteComponentProps = DefaultRouteProps & {
  component: React$ComponentType<*>,
};

export const Route = (props: RouteComponentProps) => (
  <props.component {...props} />
);

export const DefaultRoute = (props: DefaultRouteComponentProps) => (
  <props.component {...props} />
);

(Note the imported types are pulled from flow-typed‘s Reach Router definition).

They’re used like so:

<Router>
  <Route component={Component} path="/somewhere" />
  <Route component={AnotherComponent} path="/somewhere-else" />
  <DefaultRoute component={YetAnotherComponent} default />
</Router>

(And yes, eventually we’ll likely migrate this project to React Router.)

This is my jam

React’s useEffect and arrays in its’ dependency array

Could I get any more arrays into that title? I’m working on a React app at the moment. Adopting hooks has made my life a bit easier. But useEffect‘s dependency array took a while to get my head around – specifically what to do if your only dependency is itself an array.

If useEffect‘s dependency array itself contains an array, like this, you get an infinite loop and effectively perform a DOS attack on your own API.

const Thing = () => {
  const [arrayOfThings, setArrayOfThings] = useState([]);

  useEffect(() => {
    // Imagine some code here to 
    // fetch things from an API
    setArrayOfThings(loadedArrayOfThings);
  }, [arrayOfThings])

  return (
    <ul>
      {arrayOfThings.map(el => (<li>{el.title}</li>))}
    </ul>
  )
}

I imagine it’s because useEffect isn’t doing a deep compare on the dependencies. So, perhaps changing it so useEffect is dependent on the length of the array will help?

useEffect(() => {
  // Imagine some code here to
  // fetch things from an API
  setArrayOfThings(loadedArrayOfThings);
}, [arrayOfThings.length])

Well, it does, but it still requests the data from the API twice – once on first render, and again after the first fetch because the length of the array changes. The fix I found is to use a second useState variable:

const Thing = () => {
  const [arrayOfThings, setArrayOfThings] = useState([]);
  const [doFetchData, setDoFetchData] = useState(true);

  useEffect(() => {
    if (doFetchData) {
      // Imagine some code here to 
      // fetch things from an API
      setArrayOfThings(loadedArrayOfThings);
      setDoFetchData(false)
    }
  }, [doFetchData])

  return (
    <ul>
      {arrayOfThings.map(el => (<li>{el.title}</li>))}
    </ul>
  )
}

The ensures the data is only loaded once. Additionally, it gives us a way to precisely control when to go and re-fetch the data (using setDoFetchData(true)). Better.