cho.sh
Truthiness of Empty Strings

Truthiness of Empty Strings

Warning

Over a year old. May be outdated

On , our team at found a bug where a lot of React components started not working. After digging for a while, we traced it to a recent change in how we checked an error.

tsx
error && <Error message={error} />;

Sometimes, an error message can be ''. When the error message is empty, we mean the error does not exist. So the program should execute normally.

Then we added ESLint to our framework, and it started complaining that Unexpected any value in conditional. An explicit comparison or type cast is required. So we switched to a loose null check.

tsx
error != null && <Error message={error} />;

However, the '' != null comparison will regard that as the error exists. This will prevent React from performing any actions because it thinks an error occurred, but it is not visible on the client side because it renders an empty string. We missed this because sometimes error is String and sometimes React.ReactNode.

bash
Welcome to Node.js v18.16.0.
Type ".help" for more information.
> '' != null
true

So

tsx
(error != null) && <Error message={error}/>`

will become

tsx
true && <Error message={""} />;

and cause the error when the error is an empty string merely from useState(""), representing no error.

In the end we had to write an error-checking function that explicitly handles React.ReactNode and String.

46FC40

Backlinks0

No backlinks found