Category Archives: Software maintenance

How to handle button clicks in React Native – Part II

Now that my Button responds to clicks (see previous post), I can program my React Native app to do something interesting in response to the click. Remember that my user is going to select a movie title from a dropdown list of movies, and then click a button to get a list of nearby movie theaters where the movie is showing.

There are REST APIs that will return the information we want. However, I’m not going to use them – at least not yet. Why not? Because I don’t want to go down a rabbit hole researching all the possible REST APIs. Even if it wouldn’t take very long, I don’t want to get sidetracked right now.

It’s important to note that if you’re building an app for business purposes, you should not lift one finger to code up your app until you’ve figured out what 3rd party services you need, and whether there is one available which will let you access it within your budget constraints. Suppose you’ve decided that you want to build an app which supplies turn-by-turn directions to every independent coffee shop across the world. This sounds kind of like a niche app, “Google Maps for coffee”. Well, just because the Google Maps app can do something like this, doesn’t mean that a REST service exists which will be available to you. Don’t make that kind of assumption! And even if the service does exist, it may not be affordable. Suppose it exists but there’s a charge for each API call… will your business model be profitable if you take into account the cost?

Since we’re not building a real app, but just messing around to become familiar with React Native, we don’t have to worry about the above business realities. Instead, I’m going to build a very simple REST API which returns a list of movie locations. By mocking the API, I can keep my flow of building the app working, and worry about third-party features later.

I can easily mock the API because I’ve got a domain name and a shared server. All I have to do is upload a PHP file with the following content:

<?php
$theaters = array();
$theaters[] = array( "name" => "Paris Theatre", "phone" => "(212)688-3800", "address1" => "4 West 58th Street", "city" => "New York", "state" => "NY", "zip" => "10019");
$theaters[] = array( "name" => "French Institute Alliance Francaise", "phone" => "(212)355-6160", "address1" => "55 East 59th Street", "city" => "New York", "state" => "NY", "zip" => "10022");
$theaters[] = array( "name" => "Roxy Cinema Tribeca", "phone" => "(212)519-6820", "address1" => "2 Avenue of the Americas", "city" => "New York", "state" => "NY", "zip" => "10013");

$out = json_encode($theaters);
echo $out;
?>

The list of movie theaters gives this static output:

[{"name":"Paris Theatre","phone":"(212)688-3800","address1":"4 West 58th Street","city":"New York","state":"NY","zip":"10019"},
{"name":"French Institute Alliance Francaise","phone":"(212)355-6160","address1":"55 East 59th Street","city":"New York","state":"NY","zip":"10022"},
{"name":"Roxy Cinema Tribeca","phone":"(212)519-6820","address1":"2 Avenue of the Americas","city":"New York","state":"NY","zip":"10013"}]

You can do that with a static HTML page if you want, it doesn’t matter. If you don’t have a server and don’t want to spend time setting one up, just reuse my URL.

I’m going to do a little copy/paste here. People rant against copying and pasting code, and there are reasons not to do it, but it’s actually pretty reasonable to do this in rapid application development of prototypes. The idea is “let’s just get this done, since the code might be thrown out tomorrow.” Yes, doing this will lead to technical debt. However, you may never have to pay off the debt, if the application is just an experiment. Further, you’re not at a stage where refactoring for reusability makes sense, yet. So I just copy the code that was used to fetch in componentDidMount, paste it, and make some small changes. Ditto for my setMovieState and handleMoviesResponse methods. Here’s what I wind up with:

...
setNearbyTheatersState(theaters) {
    this.setState({
        isLoading: false,
        nearbyTheaters: theaters,
    });
}
...
handleNearbyTheatersResponse(theaters, delay) {
    if (delay && delay > 0) {
        const timer = setTimeout(function () {
            this.setNearbyTheatersState(theaters);
        }.bind(this), delay);
    } else {
        this.setNearbyTheatersState(theaters);
    }
}
...
handleClick() {
    console.log("handleClick");
    return fetch('https://www.fullstackoasis.com/rnb/theaters.php')
        .then((response) => response.json())
        .then((responseJson) => {
            // TODO FIXME handle timeout / delay
            this.handleNearbyTheatersResponse(responseJson);
        })
        .catch((error) => {
            // TODO FIXME replace the red screen with something informative.
            console.error(error);
        });
}
...

This is pretty much a repeat of the REST call to get the list of movies, only now I’m calling my own mocked API, and setting a state parameter named “nearbyTheaters”. Looks good! But when I click the button, I see a RedBox which reads "TypeError: _this2.handleNearbyTheatersResponse is not a function. (In '_this2.handleNearbyTheatersResponse(responseJson)', '_this2.handleNearbyTheatersResponse' is undefined)".

You might think that copy/paste didn’t work so well for us… but I’d disagree. It got us to an error faster than if we wrote all the code from scratch. Now it’s just a matter of figuring out what’s gone wrong.

To help debug this problem, I add a comment just before the call to this.handleNearbyTheatersResponse:

handleClick() {
    console.log("handleClick");
    return fetch('https://www.fullstackoasis.com/rnb/theaters.php')
        .then((response) => response.json())
        .then((responseJson) => {
            // TODO FIXME handle timeout / delay
            console.log(this);
            this.handleNearbyTheatersResponse(responseJson);
        })
        .catch((error) => {
            // TODO FIXME replace the red screen with something informative.
            console.error(error);
        });
}

Then I click the button again. I see the following logged in my terminal:

{"accessibilityLabel": undefined, "accessibilityRole": "button", "accessibilityStates": [], "background": {"attribute": "selectableItemBackground", "type": "ThemeAttrAndroid"}, "children": <RCTView style={[[Object]]}><ForwardRef(Text) style={[Array]}>FIND MOVIE NEAR ME</ForwardRef(Text)></RCTView>, "disabled": undefined, "hasTVPreferredFocus": undefined, "nextFocusDown": undefined, "nextFocusForward": undefined, "nextFocusLeft": undefined, "nextFocusRight": undefined, "nextFocusUp": undefined, "onPress": [Function handleClick], "testID": undefined, "touchSoundDisabled": undefined}

At this point I was a little puzzled; it looked to me like this was a reference to my Button, and not my app. I expected the latter. Here’s the relevant part of the render method, again:

<Button onPress={this.handleClick} title="Find Movie Near Me"></Button>

In fact, JavaScript’s correct behavior is a little hazy to me. I could find discussions that made claims about the standard behavior, but no references to the specification, and I didn’t go hunting for the official answer. Let’s not waste time tracking this down right now. Let’s assume this refers to the Button being pressed. That may be useful in some cases, but in my case, I want this to reference the app itself so that I can call handleNearbyTheatersResponse within the handleClick method.

I took a stab at fixing the problem by binding the Button‘s onPress method to this:

<Button onPress={this.handleClick.bind(this)} title="Find Movie Near Me"></Button>

That worked! Once I do that, clicking the button does not produce an error. The call to setState in setNearbyTheatersState is made. I verified this by adding a new Picker which is populated with theater listings if this.state.nearbyTheaters exists.

Here’s the new code in my render method:

if (this.state && !this.state.isLoading) {
    let items = [];
    var length = this.state.dataSource.length;
    for (var i = 0; i < length; i++) {
        var item = this.state.dataSource[i];
        // Really, really important to not put quotes around these braces:
        items.push(<Picker.Item label={item.title} value={item.title} key={item.id} />);
    }
    var theatersPicker = null;
    if (this.state.nearbyTheaters) {
        let theaters = this.state.nearbyTheaters.map(function (t, i) {
            return <Picker.Item label={t.name} value={t.name} key={i} />;
        });
        theatersPicker = <Picker>{theaters}</Picker>
    }
    return <View>
        <Picker selectedValue={this.state.movie}
            onValueChange={(itemValue, itemIndex) =>
                this.setState({ movie: itemValue })
            }>
            {items}
        </Picker>
        <Button onPress={this.handleClick.bind(this)} title="Find Movie Near Me"></Button>
        {theatersPicker}
    </View>;
    ...

The source code for this experiment is available online.

If you found this interesting, click the subscribe button below! I write a new post about once a week.

How to add a progress loader in React Native

In my last post, I took a look at how network latency might affect my React Native app, and I didn’t like what I saw: a pure white screen for several seconds. How is a user supposed to “react” to that? (Pun intended!)

It was pretty clear what was happening. My app’s render method just shows a blank view if it has no state. Here’s the render method:

render() {
    if (this.state && !this.state.isLoading) {
        ...
    } else {
        return (<View></View>);
    }
}

That’s my white screen. There’s a super simple fix:

render() {
    if (this.state && !this.state.isLoading) {
        ...
    } else {
        return (<View><Text>waiting...</Text></View>);
    }
}

Now there’s text which reads “waiting…” at the top. That’s okay for a hobby app. You’re probably going to want that to look a little nicer, however. How about a progress indicator? Something that shows “we’re working on this!”. React Native comes with an ActivityIndicator which does what we want. I’m going to grab some of the code from their documentation and add it to my app. In the render method below, I’ve replaced my “waiting” text with an ActivityIndicator (and I’ve shown the import statement to remind you to add that as well).

import { View, Text, Picker, ActivityIndicator } from 'react-native';
...
render() {
    if (this.state && !this.state.isLoading) {
        ...
    } else {
        return (<View><ActivityIndicator size="large" color="#0000ff" /></View>);
    }
}

That helps some, but the progress indicator still doesn’t look very nice. It’s placed at the very top of the screen, like this:

It turns out to be pretty easy to move the ActivityIndicator to the center of the screen. You just have to add some style components to its container View, like this:

render() {
    if (this.state && !this.state.isLoading) {
        ...
    } else {
        return (<View style={[{ flex: 1, justifyContent: 'center' },
            { flexDirection: 'row', justifyContent: 'space-around', padding: 10 }]}>
            <ActivityIndicator size="large" color="#0000ff" />
        </View>);
    }
}

Here’s the result:

With very little trouble at all, I’ve now got a slick little widget to let people know that something is going on. It’s not really enough, though. What if the network request times out, and I get an error? I’ll have to delve into that more deeply later. To remind me to do this, I’ll add a TODO/FIXME comment in the code, and open an issue in my issue tracker.

If you found this interesting, click the subscribe button below! I write a new post about once a week.

What causes “SyntaxError: JSON Parse error: Unrecognized token ‘<'" in React Native?

TL;DR: In React Native, you will get “SyntaxError: JSON Parse error: Unrecognized token ‘<‘” if your URL returns a 404 error, or in general if the content is not a JSON string.

In a recent post, I showed how to display a list of movies that had been fetched from a REST API. It worked great, but I wondered what would happen to my app’s user if their device was offline, or if the REST API ever went down. To mimic this behavior, I changed the URL by adding the number 1 at the end of it, like this: “https://facebook.github.io/react-native/movies.json1”.

And here’s what I saw in the emulator:

SyntaxError: JSON Parse error: Unrecognized token ‘<‘

The red screen says “SyntaxError: JSON Parse error: Unrecognized token ‘<‘”. That may be confusing, although if you work with REST APIs for any time, you’ll soon come to recognize what it means. Meantime, how do we investigate this?

When I load up this test URL in a web browser, I see content which looks like this:

<!DOCTYPE html>
<html>
  <head>
  ...Page not found...
</html>

It’s a fancy 404 error page. That explains why response.json barfs on this; it’s not JSON. Your app expected a JSON string. It tried to parse the string into a JavaScript object, and couldn’t handle a non-JSON string. As a reminder, here’s that fetch call:

componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json1')
        .then((response) => response.json())
        .then((responseJson) => {
...
        })
        .catch((error) => {
            // TODO FIXME replace the red screen with something informative.
            console.error(error);
        });
}

In the longer term, I will want to replace that red screen of death with a nice error page which instructs the user what to do. I’m still developing my application, however, and as a dev, I’d rather see the stack trace for errors like this when they occur.

So to deal with this, I’ll do two things: 1) I’ll add a “TODO FIXME” note in my code. When I’m cleaning up code in the end stages of development, I know to look for these types of comments which indicate work still needs to be done. 2) I’ll open an issue in my issue tracker which will let everyone on my team know that there’s something that still has to be handled in building the application. I’ll bring this to the attention of anyone who needs to know (a project manager, perhaps). The project manager may assign a designer to build a page with some graphics or specific text to display to the user in case of this error.

If you found this interesting, click the subscribe button below! I write a new post about once a week.

How to comment your MySQL database

Technically, I’m not a database administrator. Practically, I write SQL statements on a regular basis. I also create new tables and add columns to existing tables with some frequency. And I’ve noticed that most people don’t “comment” their databases. This is probably fine for scratch projects that never make it to production and are only ever maintained by one person. However, if there’s the slightest chance that someone else might be maintaining the database that you created, it’s a good idea to comment your database, just as a developer will comment their code.

Here’s an example of how you do it in MySQL:

CREATE TABLE `prices` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'table index',
  `ticker` varchar(16) NOT NULL COMMENT 'stock ticker symbol, e.g. GOOG',
  `day` date NOT NULL COMMENT 'date of price info for this stock ticker',
  `open` DECIMAL(20, 8) DEFAULT NULL COMMENT 'opening price for this stock',
  `close` DECIMAL(20, 8) DEFAULT NULL COMMENT 'closing price for this stock',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='record of opening and closing prices for stock' AUTO_INCREMENT = 1000;

If you’re adding a column to a table, you can comment it at the same time, like this:

ALTER TABLE prices ADD COLUMN `volume` int(11) DEFAULT 0 COMMENT 'trading volume for this stock' AFTER `close`;

In my example, the columns and their names might seem obvious to people who are remotely savvy with finance. But just because you know something about finance, doesn’t mean the next dev will have this somewhat specialized knowledge. Your comment can help them find the information they need to understand what the column means and how to use it. Furthermore, in many business applications, database schemas may consist mostly of fields which only have meaning within the business itself. Comments on those fields can be a very handy source of documentation when the original developers are long gone.

As an aside, my prices table is only an example table for holding stock prices. You can see I really went overboard in allowing 8 decimal places for a stock price. Let’s just say I “future-proofed” it. Here’s a sample INSERT statement:

INSERT INTO prices (ticker, day, open, close) values ('GOOG', '2059-12-21', 401200022445.09787456, 401200023899.09787456);
SELECT * FROM prices;
+------+--------+------------+-----------------------+-----------------------+
| id   | ticker | day        | open                  | close                 |
+------+--------+------------+-----------------------+-----------------------+
| 1000 | GOOG   | 2059-12-21 | 401200022445.09787456 | 401200023899.09787456 |
+------+--------+------------+-----------------------+-----------------------+
1 row in set (0.00 sec)

And here’s the CREATE TABLE statement as viewed by a developer trying to figure things out:

SHOW CREATE TABLE prices;
...
| prices | CREATE TABLE `prices` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'table index',
  `ticker` varchar(16) NOT NULL COMMENT 'stock ticker symbol, e.g. GOOG',
  `day` date NOT NULL COMMENT 'date of price info for this stock ticker',
  `open` decimal(20,8) DEFAULT NULL COMMENT 'opening price for this stock',
  `close` decimal(20,8) DEFAULT NULL COMMENT 'closing price for this stock',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8 COMMENT='record of opening and closing prices for stock' |
1 row in set (0.00 sec)

If you found this interesting, click the subscribe button below! I write a new post about once a week.