A NativeScript Beer App (TypeScript)
Using HTTP to process JSONdata
First a shout out to Horacio Gonzalez and his NativeScript Beers Tutorial. This post is an update of that post.
In this tutorial, we will create a NativeScript app that will get http json data from http://www.beer-tutorials.org/beers/beers.json. Here is an image of the finished product.
First, you will need to do is ensure you have NativeScript installed. Here is the Quick Setup Guide.
After installing NativeScript, create a new project called nativescript-beers
.
tns create nativescript-beers
Now choose Plain TypeScript and the Hello World Template.
This is one of the features I love about NativeScript. The generators give you the scaffolding for functional apps right out of the box.
Now change to the nativescript-beers folder (created with the command above) and run.
tns run ios
It's obvious, but be advised the command above opens whatever your default emulator is. For Android, you can run tns run android.
There is also a cool new feature in NativeScript 5 that is tns preview
that will allows you to run the app on your local device. You will need the Playground App installed on your device to use this.
No matter how you are previewing the app you should see something similar to the screen below.
Go ahead and tap the button until it counts down to 0. Spoiler alert, your socks will not be blown off by the easter egg at the end, but you have to do it at least once. 😉
Go ahead and open the app in your favorite editor. Pro Tip: VS Code is the editor of choice for NativeScript (and TypeScript for that matter). How tidy is this file folder structure?! Coming from the Rails world I love the common structure that all NativeScript apps share. Even if you have never seen a NativeScript app before, just looking at this structure, you already have a sense of what the app does and pages it might contain. All the good stuff is in the App folder, so I won’t discuss anything outside of that for this tutorial. Horacio does a pretty good job of explaining what the other files/folders do in his tutorial and most of that is still relevant, so check out the Project Structure section of his tutorial to read more about that.
Designing the App
First, let's start by modifying the main page of the app. We want the button to say “Get Me Beers”, so you can probably figure out how to do that without me even telling you. Simply open app/main-page.xml
and change “Tap the button” to “Get Me Beers” and save the file.
<Label text=”Get Me Beers” class=”h1 text-center”/>
Automagically the button in your app should now say “Get Me Beers”. 😃 If that does not make you happy, then stop reading this tutorial right now and go smash your fingers with a hammer. Yes, NativeScript live loads your code as you make changes making for a harmonious development experience. Ok, now let's make main-page.xml
look like this:
This will give you this…
Not much here. We just changed the title and button text, and also added verticle orientation to your StackLayout. The orientation doesn’t do anything for us yet, but it will when we start loading beers.
Getting Data from the API
Now the fun part. Let’s start pulling data from http://www.beer-tutorials.org/. Specifically the JSON feed we will be using is http://www.beer-tutorials.org/beers/beers.json.
The first thing we will do is add a function to main-page.ts that will fire when the user taps the “Get Me Beers” button. Go ahead a delete everything in main-page.ts
and add this function:
exports.beers = function() {
console.log("Export Beers Function Called")
};
Save the file and now click the button in the app. Nothing happens in the app, but if you look at your console you should see something like:
CONSOLE LOG file:///app/main-page.js:2:16: Export Beers Function Called
Each time you click the button you should see this message logged. Now that our button is tied to a function lets make the function fetch our JSON data via HTTP.
We’re doing two things here. At the top of the file, we import the NativeScript HTTP Module along with the getJSON
method. Then (using the getJSON method) we get the JSON data and log it to the console.
Go ahead and click the button and check out the results in the console. If you are using an Android emulator you are good, but if you are on iOS you will get a “…App Transport Security policy requires the use of a secure connection…” error (google it to read more about it). To remedy that you will you will need to modify app/App_Resources/iOS/Info.plist
with:
Be sure to put this just inside (above) the final closing </dict> tag in this file. You can read more about it HERE.
With that out of the way iOS and Android users should be good. When you click the “Get me Beers” button you should see something like this in the console:
That’s a beautiful thang! Now we just need to get this data in an array, hand it off to the UI, and display it.
First, let’s get the data into an array and also create an onPageLoaded function that we will call from the view:
OK…a lot of code here, but let’s walk through it. At the top, we have some new lines of code. First, we import Observable
and ObservableArray
modules. The Observable
module binds data in the view (more on this later) and the ObservableArray
module is NativeScripts own implementation of an array and allows for common array functions like concat, push, reduce, slice and splice. Next, we create a new variable called beerList that we will use to store the JSON data and the other variable pageData is used in the onPageLoaded function to bind data to the View.
The View
OK, now that we have data staged up and ready to be displayed, let’s show it to the user.
It’s 20 lines of code, but if you have done any coding at all, this should not be terribly intimidating. NaiveScript uses XML for all of its views, and even though most of us would rather have a root canal than deal with XML, it's actually pretty refreshing in that is just plain old opening/closing tags along with some {{ }} to handle variables and data. However, there are a couple of things I want you to note.
- The
loaded=”onPageLoaded”
in the opening Page tag is binding this view to the onPageLoaded function we created earlier in main-page.ts. - In line 8 we are loading the beerList array from main-page.ts
- Lines 11, 13 and 14 are displaying the beer image, name and description respectively
One last thing, just a tiny bit of CSS to put in app/app.css:
.btn {
font-size: 18;
}
OK, the moment of truth. Save all your files and click the “Get Me Beers” button and voila! You should see one of the images below in your emulator. 😃
You can view the repo for this code here. Also, you go HERE to run the app on your phone using the playground app. Check out this presentation on NativeScript where I live code this tutorial.
Now a call to action! If you are a Vue or Angular nerd NativeScript also supports these frameworks, so create a version of the app in one of those and post a link in the comments below.
Happy Coding! 😎