<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[React Native Development - Medium]]></title>
        <description><![CDATA[The best about React-Native development - Medium]]></description>
        <link>https://medium.com/react-native-development?source=rss----294c69a8d75c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>React Native Development - Medium</title>
            <link>https://medium.com/react-native-development?source=rss----294c69a8d75c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:52:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/react-native-development" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Tutorial: Making dVPN desktop application with Electron & React]]></title>
            <link>https://medium.com/react-native-development/tutorial-making-dvpn-desktop-application-with-electron-react-da3b9aba5365?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/da3b9aba5365</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[dvpn]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Andrey Nikishaev]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 08:18:36 GMT</pubDate>
            <atom:updated>2021-10-25T08:18:35.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*NcSJqmWR1sR2CkFF.png" /></figure><h3>Making client application.</h3><p>Hello friends, in this tutorial we will show how to build the simplest desktop dVPN application based on the Electron framework and will cover the main parts of the dVPN client, to give you an understanding of how they interact.</p><p>For those who want’s to go straight to the code, <a href="https://github.com/creotiv/dvpn-tutorial-mysterium-network">here is a link</a></p><p>What we will use:</p><ul><li>NodeJs: &gt;=v16.9.1</li><li>npm: &gt;=7.21.1</li><li>yarn: &gt;= 1.22.5</li><li>Electron: &gt;= 14.0.1</li><li>Typescript: &gt;= 4.4.3</li><li>webpack: == 4.46.0 <em>// we can’t use Webpack 5, because of limitation in electron-webpack</em></li><li>electron-webpack: &gt;= 2.8.2</li><li>React: &gt;= 17.0.2</li><li>@mysteriumnetwork/node: &gt; 0.64.0 <em>// Client Mysterium Node</em></li><li>mysterium-vpn-js: &gt; 15.1.0 <em>// Tequila API client</em></li><li>electron-builder: &gt; 22.11.7</li></ul><h3>How is client application work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*oXmpI_JcVHgppXeO.png" /></figure><p>Every client application consist of these four parts:</p><ul><li>Application — your client application</li><li><a href="https://github.com/mysteriumnetwork/node">Mysterium Node </a>— client node to interact with Mysterium Network</li><li>Supervisor — service used to move out from Node any services that need escalation of privileges, and also used to control them. Supervisor used only for client applications.</li><li><a href="https://www.wireguard.com/">Wireguard</a> — VPN tunnel</li></ul><p>Typical application startup:</p><ol><li>Start the Node.</li><li>Install &amp; Start Supervisor service(if it has not been installed yet).</li><li>Setup connection to the Node Tequila API through the localhost.</li><li>Setup connection to the Supervisor through the socket.</li><li>Do some application logic…</li></ol><p>Each Mysterium client Node is running Tequila API on `localhost:44050` which is used for communication and control. To interact with this API we will use the package `mysterium-vpn-js`. You can see docs for API by opening <a href="http://localhost:44050/docs">localhost:44050/docs</a> in your browser(when Node working) and by visiting <a href="https://github.com/mysteriumnetwork/mysterium-vpn-js/blob/master/src/tequilapi-client.ts">mysterium-vpn-js</a> client</p><h3>Let’s build some simple Electron App</h3><p>Clone our demo repository to your local machine</p><ol><li>git clone <a href="https://github.com/mysteriumnetwork/dvpn-desktop-tutorial">https://github.com/mysteriumnetwork/dvpn-desktop-tutorial</a></li><li>yarn install</li><li>yarn dev - to see how it looks like</li></ol><h3>Structure &amp; main modules</h3><p>Usually, people are building react app with the use of create-react-app tool which separates Source code from Electron. But this approach has some negative consequences if we want that all our code to be written on TypeScript. That&#39;s why we will be using webkit &amp; electron-webkit wrapper.</p><p>From this point our project structure will look like this:</p><pre>|static             // static files<br>|---bin             // place where bin from @mysteriumnetwork/node will be copied<br>|src                // our code<br>|---electron        // electron part with main process<br>|---|---node        // IPC Host code<br>|---renderer        // app part<br>|---|---api         // api methods to work with Tequila API<br>|---|---components  // UI components<br>|---shared          // shared code, libraries, utils<br>|---|---ipc         // IPC clients</pre><p>In electronWebpack part of package.json we set location of our app parts like electron and app, also adding webpack config for renderer process.</p><p>We use postinstall directive to copy Node binaries to our static folder so we could get access to them later from the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89b612c592e0fb51fed9fd67a5c969de/href">https://medium.com/media/89b612c592e0fb51fed9fd67a5c969de/href</a></iframe><h3>Setting up Electron</h3><p>The first entry point of our application is src/electron/main.ts which will run our Electron. To create an Electron window we use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bdfbc1ddd7e898ad286674c9ff4b207/href">https://medium.com/media/8bdfbc1ddd7e898ad286674c9ff4b207/href</a></iframe><p>Besides typical stuff, we need to setup IPC channels for our Node and Supervisor. And stop Node and disconnect from Supervisor before quit</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1663bb62b55bb01f3df3af8f7bfaf531/href">https://medium.com/media/1663bb62b55bb01f3df3af8f7bfaf531/href</a></iframe><h3>Mysterium Node &amp; Supervisor</h3><p>In the src/electron/node/ we have mysteriumNode.ts and supervisor.ts. This is our IPC listeners that runs in the Electron thread, and which will give our App the possibility to run Node and Supervisor. We need this because our renderer process with our app has no access to the system, but the electron process has.</p><p>We will communicate with them using IPC clients in src/shared/ipc folder.</p><p>In mysteriumNode.ts we have 3 IPC methods: start, stop and kill. If you need Import/Export identity methods you can find them <a href="https://github.com/mysteriumnetwork/mysterium-vpn-desktop/blob/master/src/main/node/mysteriumNode.ts">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469f708b0deee04fab95aae60f2e1996/href">https://medium.com/media/469f708b0deee04fab95aae60f2e1996/href</a></iframe><p>In supervisor.ts we have 4 IPC methods: install, upgrade, connect, disconnect. During Supervisor installation user will need to enter Admin password as it will be run with system privileges.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7db0dd734b976e32923dd0638b8d999/href">https://medium.com/media/d7db0dd734b976e32923dd0638b8d999/href</a></iframe><h3>Main App</h3><p>Our application is very simple and consists of a few views components and API to work with Node Tequila API.</p><p>Let’s discuss the process of interaction with Node and creating VPN tunnel with some exit nodes:</p><p>1. We need to create an identity, which looks something like this 0x142362c0a179da288903f21adcba24686c01e654 and which is basically user id in Mysterium Network</p><p>2. To use identity we need to unlock it(with a password) and register in the Registry service of Mysterium Network.</p><p>3. Get a list of proposals using some filtration by country, connection type, price, speed, etc. The proposal is information about the provider(exit node) to which you are able to connect.</p><p>4. Connect to one of the providers and all traffic will be routed through him.</p><p>5. Disconnect from the provider to stop route traffic through him.</p><p>We will not be using any redux, mobx, etc. Instead, we will store state in the api.ts to make the app simpler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9350efcf6e21ede64510117884c78220/href">https://medium.com/media/9350efcf6e21ede64510117884c78220/href</a></iframe><p>We use steps here instead of a router to just update the App view on State update in the API.On startup, we calling Startup() and Preload() to start the Node and the Supervisor and preload identities list with current connection status(if we reload the app during work)</p><p>After that, all pretty simple -&gt; User select identity(or create new), unlock it, and connect to random Node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79c0bb8783bdb3efee594553d7527b83/href">https://medium.com/media/79c0bb8783bdb3efee594553d7527b83/href</a></iframe><h3>Summarize</h3><p>As you can see building dVPN application for Mysterium Network is simple enough. Just a few files for Node and Supervisor integration, Tequila API to control the Node and that’s all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da3b9aba5365" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/tutorial-making-dvpn-desktop-application-with-electron-react-da3b9aba5365">Tutorial: Making dVPN desktop application with Electron &amp; React</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Become an Object Detection Expert]]></title>
            <link>https://medium.com/react-native-development/become-an-object-detection-expert-cffd00ed47e5?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/cffd00ed47e5</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[udemy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coursera]]></category>
            <dc:creator><![CDATA[Andrey Nikishaev]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 14:52:22 GMT</pubDate>
            <atom:updated>2020-01-04T14:52:21.044Z</atom:updated>
            <content:encoded><![CDATA[<p>Computer Vision is the widest and most highly paid area in Machine Learning. While it solving many hard tasks, Object Detection is one of the most popular as it used in robotics, drones, self-driving cars, satellite analytics, photography, video production, etc. And today we offering you the Number One Practical Online Course on Object Detection which will teach you how to solve real-life problems.</p><p>We are not the same course as on Coursera, Udemy, edX, etc. Our main task not to give you just dry theory not linked to real life, like everyone do, but make a specialist with deep problem and models understanding who can compete on the global market.<br>The whole course is built with the use of Google Colab Notebooks that put theory and practice side-by-side and describes each step in our journey.</p><p>You will not find something similar on the internet, because this course was developed by the field developer for developers.</p><p>Learn more here: <a href="https://learnml.today">https://learnml.today</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffd00ed47e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/become-an-object-detection-expert-cffd00ed47e5">Become an Object Detection Expert</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily Build Forms in React Native]]></title>
            <link>https://medium.com/react-native-development/easily-build-forms-in-react-native-9006fcd2a73b?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/9006fcd2a73b</guid>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Spencer Carli]]></dc:creator>
            <pubDate>Thu, 21 Sep 2017 13:10:16 GMT</pubDate>
            <atom:updated>2017-09-20T20:46:12.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OULxgHA3QB60xpOlUJg0QA.jpeg" /></figure><p>If you’re building a React Native app it’s almost a guarantee that you’ll have to build at least one form. The reality is you’ll probably build quite a few (sign in, sign up, edit profile, etc.)</p><p>Forms are pretty simple, right?</p><p>Yeah! But there can be quite a few moving parts involved. A few things you might have to take care of…</p><ol><li>Creating the necessary components (text inputs, select inputs, checkboxes, switches, etc)</li><li>Writing/finding validation logic</li><li>Updating your components to display any errors (I always forget to do this)</li><li>Updating your UI whenever you change fields</li></ol><p>None of these things are difficult, but they can be time consuming. Especially if you’re trying to ship something quickly.</p><p>In the past I’ve always done all of this myself. But it takes time away from what I <em>really</em> want to be doing.</p><p>I started looking around for solutions to solve this problem and came across <a href="https://github.com/gcanti/tcomb-form-native">tcomb-form-native</a>. It makes creating forms in React Native easy by simply having to define a model for that form and you’re set! No fussing around with a dozen components.</p><h3>Setup</h3><p>To get started I’ve <a href="https://snack.expo.io/SyVq4Egsb">put together a Snack</a> that will allow us to do all of our work on the web. It’s an awesome tool.</p><p>You’ll notice at the top of the file I’ve added import t from &#39;tcomb-form-native&#39;; which is the library we’ll be using to build our form. Snack will automatically pull that in for us.</p><blockquote>Tip: I find that scanning the QR code from the Expo app on my device gives the best development experience.</blockquote><p>If you prefer to do this outside of Snack make sure you install tcomb-form-native via npm or yarn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0y6K0RzkZMtyjTQtimF4w.png" /></figure><h3>What We’re Building</h3><p>We’ll be building a sign up form that has the following fields</p><ul><li>Email (required)</li><li>Username (optional)</li><li>Password (required)</li><li>Agree to terms (required)</li></ul><h3>Defining the Form Model</h3><p>The first thing we need to do is define a model for our form — this is what will be passed to the form component and used to render the fields.</p><p>When defining the model we need to specify at minimum the field and the type of value that it accepts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4855571a9512a31cebe20f861e93311a/href">https://medium.com/media/4855571a9512a31cebe20f861e93311a/href</a></iframe><p>We’re just using a few of the different types but there are <a href="https://github.com/gcanti/tcomb-form-native#types">more available</a>.</p><p>Let’s go ahead and actually render this form to see what we’ve got. First we need to get the Form component (line 6) then we need to render the form and pass our model to it as the type (line 19).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561c70ae6160e6fdba700b6451774c38/href">https://medium.com/media/561c70ae6160e6fdba700b6451774c38/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*RTgUEW2kUa7_ILP10jo5dA.png" /></figure><h3>Capturing Form Data</h3><p>Good start! Now let’s actually try to capture that data. We’ll just use the basic Button component (which comes from react-native) to do this and add a handleSubmit function to the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13b47cb660da9a074f50030690bfeb20/href">https://medium.com/media/13b47cb660da9a074f50030690bfeb20/href</a></iframe><p>Now to actually access and work with our form we need to add a reference to it and with that we should be able to call getValue() from handleSubmit .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b94b6c5ae657d424d3e5ddcbd81e9506/href">https://medium.com/media/b94b6c5ae657d424d3e5ddcbd81e9506/href</a></iframe><p>However when you press “Sign Up” all the fields go red — automatic validation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*xpeORAnSxOc8w7-2KW8SvA.png" /></figure><p>That’s coming from when we defined our model earlier. However, the username should be an optional field. Let’s fix that.</p><h3>Customizing the Form</h3><p>To do that we’ll use t.maybe to tell tcomb it’s an optional field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91ad427c584112219b743f4d5a423ff/href">https://medium.com/media/a91ad427c584112219b743f4d5a423ff/href</a></iframe><p>Boom. That easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*_7O9YFjwCs6xOsioAWOvsg.png" /></figure><p>I also want to change the label for the “Terms” field. I want it to say “Agree to Terms” — we can do this via options passed to the Form.</p><p>This part is a bit verbose but it makes sense the way it’s set up. We create an object, add a key named “fields” (since we’re modifying the fields), add a key to this object that aligns with the key in our model (“terms”), and then inside that object we set the new label.</p><p>Code is easier to understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de0d4b3450711695bf820e1d24de8e68/href">https://medium.com/media/de0d4b3450711695bf820e1d24de8e68/href</a></iframe><p>Then pass those options to the Form component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c764069516c540f25f2392ffc911f2c1/href">https://medium.com/media/c764069516c540f25f2392ffc911f2c1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*CmaTQAiiwPt1LyphJutLEg.png" /></figure><p>Let’s do the same thing to add some error messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddc326a11c51a74ce94575a7a300d924/href">https://medium.com/media/ddc326a11c51a74ce94575a7a300d924/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*zuqdDCVANVkI31-fM7XcDA.png" /></figure><h3>Modifying the Form Design</h3><p>The final thing I want to do is modify the design of this form slightly. You can do <a href="https://github.com/gcanti/tcomb-form-native#stylesheets">quite a few things</a> but I’m just going to be changing the label color on this one form.</p><p>The first thing I’m going to do is create a new formStyles object and copy over all of the default styles so I don’t have to start from scratch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a444dead55566b56bb18d99d69c58dfd/href">https://medium.com/media/a444dead55566b56bb18d99d69c58dfd/href</a></iframe><p><a href="https://github.com/gcanti/tcomb-form-native/blob/master/lib/stylesheets/bootstrap.js">Here’s the full default stylesheet</a>.</p><p>Then I’ll customize it with my A+ design skillz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d0c4423be23c9cc0298d7550d2d6fab/href">https://medium.com/media/5d0c4423be23c9cc0298d7550d2d6fab/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*0DYsS4myJdmTZlpgMbEM9A.png" /></figure><p>Simple &amp; beautiful design modifications. Just about everything in the default form is customizable.</p><p>As you can see tcomb-form-native makes building forms quick and easy but also gives you the flexibility you need to create forms the give users the necessary info and fit with the rest of your app (unless I’m designing of course).</p><p>You can get the <a href="https://snack.expo.io/SJiexSeiW">final code on Snack</a>.</p><p>And that’s all, folks! I’ve just scratched the surface of what this package is capable of. I encourage you to try it out in your apps! (And make sure to thank the package author — open source ain’t easy!)</p><blockquote>If you found this helpful consider taking my <a href="http://reactnativebasics.com">free React Native course</a> which will get you up and running 500% faster than if you do it on your own (I made that number up).</blockquote><p>✌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9006fcd2a73b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/easily-build-forms-in-react-native-9006fcd2a73b">Easily Build Forms in React Native</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning is a new trend. Here is good starting point for those who interested.]]></title>
            <link>https://medium.com/react-native-development/machine-learning-is-a-new-trend-here-is-good-starting-point-for-those-who-interested-22fcf8c814eb?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/22fcf8c814eb</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Andrey Nikishaev]]></dc:creator>
            <pubDate>Sat, 19 Aug 2017 23:14:36 GMT</pubDate>
            <atom:updated>2017-08-19T23:14:36.365Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi guys, it’s been a while since my last letter. I was on my strange vacations. Strange, because all this time i was learning Machine Learning and Computer Vision, and it’s damn interesting thing. <br>That why i wrote small article about my learning path in this are, for those who also interested in this and don’t know from where to start.</p><p>You can read it here: <a href="https://hackernoon.com/learning-path-for-machine-learning-engineer-a7d5dc9de4a4">https://hackernoon.com/learning-path-for-machine-learning-engineer-a7d5dc9de4a4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22fcf8c814eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/machine-learning-is-a-new-trend-here-is-good-starting-point-for-those-who-interested-22fcf8c814eb">Machine learning is a new trend. Here is good starting point for those who interested.</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Build a React Native HackerNews app where people are nice]]></title>
            <link>https://medium.com/react-native-development/tutorial-build-a-react-native-hackernews-app-where-people-are-nice-b591aca86727?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/b591aca86727</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hacker-news]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Sat, 12 Aug 2017 00:54:29 GMT</pubDate>
            <atom:updated>2017-08-11T12:43:33.288Z</atom:updated>
            <content:encoded><![CDATA[<p>This week’s app idea comes from Dan Abramov: A Hacker News app where people are nice. We’re going to use <a href="https://github.com/HackerNews/API">HN’s official Firebase API</a> to load stories and comments, Google’s <a href="https://cloud.google.com/natural-language/">Natural Language API</a> to hide negative comments, <a href="https://mobx.js.org/">MobX</a> for state management, Shoutem UI Toolkit for styling, and <a href="https://github.com/jsdf/react-native-htmlview">react-native-htmlview</a> to render HTML as a tree of native Text components.</p><h3>Dan Abramov 🌴 on Twitter</h3><p>Tutorial idea: building a Hacker News clone where people are nice</p><p>Our HackerNews app where people are nice lets you browse stories by category and read their comments. Each comment shows whether it is neutral or positive. Negative comments are hidden. Posting comes later, this is an MVP.</p><p>Click “3 replies”, 1 shows up. Click “1 reply”, 0 show up. That’s Google’s Sentiment Analysis hiding things that are negative. You’re welcome.</p><p>To be honest, I was surprised by the amount of negativity on Hacker News. I knew it was bad, but I didn’t think it was <em>that</em> bad until I ran it through Google’s Natural Language API.</p><p>Here’s a quick breakdown for a frontpage story, <a href="https://news.ycombinator.com/item?id=14741124"><em>“Using Tesseract OCR with Python”</em></a>. Somebody shares what they’ve built: 6 negative comments, 6 neutral comments, 8 positive comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*-UUJ2nlqg83hF_qy.png" /></figure><p>Let’s build our app. You can see the <a href="https://github.com/shoutem/school/tree/master/HackerNewsApp">full code on GitHub</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FpZI62EwsyHo%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DpZI62EwsyHo&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FpZI62EwsyHo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfc0d75dfd4ad7026d8868f2168336b5/href">https://medium.com/media/cfc0d75dfd4ad7026d8868f2168336b5/href</a></iframe><h3>Setup</h3><p>Before we begin, we’ll need some dependencies and a new React Native project. Remember to use 0.43.3 so we can use Shoutem UI.</p><pre>react-native init HackerNewsApp --version=react-native@0.43.3<br>cd HackerNewsApp<br>npm install --save @shoutem/ui mobx mobx-react firebase lodash prop-types react-native-htmlview<br>react-native link</pre><p>That gives you the default app.</p><p>We should enable decorators because they make MobX nicer to use. No sweat if you don’t like them, it works without. I think they make our code easier to read though.</p><pre>npm install --save babel-preset-react-native-stage-0</pre><p>And edit .babelrc.</p><pre>// .babelrc<br>{<br>&quot;presets&quot;: [&quot;react-native&quot;, &quot;react-native-stage-0/decorator-support&quot;]<br>}</pre><p>To finish setting up our project, we create a src/ directory and change index.ios.js or index.android.js to render our &lt;App&gt; component. This particular app should work unchanged on both iOS and Android.</p><pre>// index.ios.js<br><br>import React, { Component } from &#39;react&#39;;<br>import {<br>  AppRegistry<br>} from &#39;react-native&#39;;<br><br>import App from &#39;./src&#39;;<br><br>export default class HackerNewsApp extends Component {<br>  render() {<br>    return (<br>      &lt;App /&gt;<br>    );<br>  }<br>}<br><br>AppRegistry.registerComponent(&#39;HackerNewsApp&#39;, () =&gt; HackerNewsApp);</pre><p>And in src/index.js we create an empty App with a MobX store.</p><pre>// src/index.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { Screen, NavigationBar, DropDownMenu, Divider, View, Text } from &#39;@shoutem/ui&#39;;<br>import { CardStack } from &#39;@shoutem/ui/navigation&#39;;<br>import { useStrict } from &#39;mobx&#39;;<br>import { Provider, observer } from &#39;mobx-react/native&#39;;<br><br>useStrict(true);<br><br>import Store from &#39;./Store&#39;;<br><br>@observer<br>class App extends Component {<br>    render() {<br>        return (<br>            &lt;Provider store={Store}&gt;<br>                &lt;Screen /&gt;<br>            &lt;/Provider&gt;<br>        )<br>    }<br>}<br><br>export default App;</pre><p>We import everything we’ll need because I know the future, set MobX to strict mode so we can’t make accidental state changes, import our Store, and create a blank App component with a Provider that makes our store globally available.</p><p>We need a blank MobX store as well.</p><pre>// src/Store.js<br><br>import { action, computed, observable, extendObservable } from &#39;mobx&#39;;<br>import * as firebase from &#39;firebase&#39;;<br>import take from &#39;lodash/take&#39;;<br><br>class Store {<br>}<br><br>export default new Store();</pre><p>A MobX store is a JavaScript object. It gains super powers when we add observers, actions, and computed values.</p><h3>MobX 101</h3><p>If you’re new to MobX, these are the basics you need to know.</p><p>MobX implements the ideas of reactive programming. There are values that are observable and functions that react when those values change. MobX ensures only the minimal possible set of observers is triggered on every change.</p><p>So, we have:</p><p>@observable – a property whose changes observers subscribe to<br> @observer – a component whose render() method observes values<br> @computed – a method whose value can be fully derived from obsevables<br> @action – a method that changes state, analogous to a Redux reducer<br> @inject – a decorator that injects global stores into a component’s props</p><p>That’s all you need to know. Once your component is an @observer, you never have to worry about <em>what</em> it’s observing. MobX ensures it reacts only to the values that it uses during rendering.</p><h3>Basic Navigation</h3><p>Our HackerNews app begins with basic navigation: A dropdown for different story types and a button to go navigate back.</p><p>One way to achieve this, is using Shoutem’s NavigationBar and CardStack components. They’re based on ReactNavigationExperimental, which has turned into ReactNavigation in recent months. More on that in <a href="https://school.shoutem.com/lectures/tutorial-build-crowdsourced-react-native-travel-app-react-navigation-asyncstorage-firebase/">my react-navigation tutorial</a>.</p><p>The visual part of basic navigation goes in our &lt;App&gt; component.</p><pre>// src/index.js<br><br>@observer<br>class App extends Component {<br><br>    renderDropDown() {<br>        return (<br>            &lt;DropDownMenu options={Store.storyTypes.slice()}<br>                          titleProperty=&quot;name&quot;<br>                          valueProperty=&quot;value&quot;<br>                          selectedOption={Store.selectedStoryOption}<br>                          onOptionSelected={storyType =&gt; Store.pickStoryType(storyType)} /&gt;<br>        );<br>    }<br><br>    renderNavBar({ navigationState }) {<br>        const route = navigationState.routes[navigationState.index];<br>        let centerComponent = null;<br><br>        if (route.type === &#39;storylist&#39;) {<br>            centerComponent = this.renderDropDown();<br>        }else{<br>            centerComponent = (<br>                &lt;Text ellipsizeMode=&quot;tail&quot; numberOfLines={1}&gt;<br>                    {Store.items.get(route.id).title}<br>                &lt;/Text&gt;<br>            );<br>        }<br><br>        return (<br>            &lt;NavigationBar hasHistory={navigationState.index &gt; 0}<br>                           navigateBack={() =&gt; Store.navigateBack()}<br>                           centerComponent={centerComponent} /&gt;<br>        );<br>    }<br><br>    renderScene({ scene }) {<br>        const { route } = scene;<br><br>        return &lt;Screen /&gt;;<br>    }<br><br>    render() {<br>        return (<br>            &lt;Provider store={Store}&gt;<br>                &lt;CardStack navigationState={Store.navigationState}<br>                           renderNavBar={this.renderNavBar.bind(this)}<br>                           renderScene={this.renderScene.bind(this)} /&gt;<br>            &lt;/Provider&gt;<br>        )<br>    }<br>}</pre><p>The code reads bottom to top. We replace the empty &lt;Screen&gt; render with a &lt;CardStack&gt; component. It creates a stackable screens effect with swipey animations when users navigate.</p><p>As props it takes:</p><ul><li>navigationState, an object with an index and a list of routes</li><li>renderNavBar, a method that renders the navigation bar</li><li>renderScene, a method that renders scenes based on routes</li></ul><p>More on navigationState when we look at our MobX Store. We use Shoutem’s NavBar and DropDown components to render the Navbar and keep renderScene empty for now. We’ll fill it in when we list stories and render individual items.</p><p>Our NavBar renders either a story title or a dropdown to switch between different types of stories. The hasHistory prop makes a back button appear when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*PbLxSeP21anNcO6H.png" /></figure><h3>MobX store support</h3><p>The code we just wrote needs some support from our MobX Store to work. We need a list of storyTypes for the dropdown, a way to store current navigationState, and actions to drive transitions.</p><pre>// src/Store.js<br><br>class Store {<br>    @observable storyTypes = [<br>        {name: &#39;Top&#39;, value: &#39;topstories&#39;},<br>        {name: &#39;Ask HN&#39;, value: &#39;askstories&#39;},<br>        {name: &#39;Show HN&#39;, value: &#39;showstories&#39;},<br>        {name: &#39;Jobs&#39;, value: &#39;jobstories&#39;}<br>    ];<br><br>    @observable _navigationState = {<br>        index: 0,<br>        routes: [<br>            {key: &#39;topstories&#39;, type: &#39;storylist&#39;}<br>        ]<br><br>    };<br><br>    @computed get navigationState() {<br>        return {<br>            index: this._navigationState.index,<br>            routes: this._navigationState.routes.slice()<br>        };<br>    }<br><br>    @computed get currentRoute() {<br>        return this._navigationState.routes[this._navigationState.index];<br>    }<br><br>    @computed get selectedStoryOption() {<br>        const { key } = this.currentRoute;<br><br>        return this.storyTypes.find(<br>            ({ name, value }) =&gt; value === key<br>        );<br>    }<br><br>    @action navigateBack() {<br>        this._navigationState.index -= 1;<br>        this._navigationState.routes.pop();<br>    }<br><br>    @action pickStoryType({ value }) {<br>        //this.listenForStories(value);<br><br>        this._navigationState.routes.push({<br>            key: value,<br>            type: &#39;storylist&#39;<br>        });<br>        this._navigationState.index += 1;<br>    }<br>}</pre><p>Here’s what I like about MobX: You can read this code even if you don’t know how MobX works. The hard stuff happens behind the scenes, you just write the business logic of your app.</p><p>We have a list of storyTypes that have a name and a key. We have a _navigationState with an index and a list of routes. Pre-filled with default values.</p><p>Then we have some computed values. They derive purely from our store. A navigationState returns a plain JavaScript version of _navigationState without MobX’s additions, and currentRoute and selectedStoryOption tell us some current state. They’re mostly helpers to make our life easier.</p><p>Our actions handle state manipulations. navigateBack pops the last navigation state from stack, and pickStoryType pushes a new one onto stack.</p><p>When state changes, MobX handles re-rendering behind the scenes.</p><h3>Listing Stories</h3><p>We need to change 3 files to render a list of stories: Add loading logic to the store, start initial fetching on App render, and render a ListView with the result.</p><h3>Store</h3><pre>// src/Store.js<br><br>firebase.initializeApp({<br>    databaseURL: &#39;https://hacker-news.firebaseio.com&#39;<br>});<br><br>const N_STORIES = 30,<br>      LANG_API_KEY = &#39;AIzaSyCSE5mekK1XxfDMQde8bywlaOMIdN5L7ug&#39;;<br><br>class Store {<br>    @observable stories = observable.map();<br>    @observable items = observable.map();<br>    @observable alreadyListening = observable.map();<br>   <br>    // ...<br>    @action listenForStories(storyType) {<br>        if (!this.alreadyListening.get(storyType)) {<br>            this.alreadyListening.set(storyType, true);<br>            firebase.database()<br>                    .ref(`v0/${storyType}`)<br>                    .on(&#39;value&#39;, snapshot =&gt; {<br>                        const ids = take(snapshot.val(), N_STORIES);<br><br>                        this.updateStories(storyType, ids);<br>                        ids.forEach(id =&gt; this.listenToStory(id));<br>                    })<br>        }<br>    }<br><br>    @action updateStories(storyType, ids) {<br>        this.stories.set(storyType, ids);<br>    }<br><br>    @action listenToStory(id) {<br>        firebase.database()<br>                .ref(`v0/item/${id}`)<br>                .on(&#39;value&#39;, snapshot =&gt; {<br>                    this.updateItem(id, snapshot.val());<br>                });<br>    }<br><br>    @action updateItem(id, val) {<br>        val.sentiment = {fetched: false};<br>        this.items.set(id, val);<br>    }  <br>}</pre><p>We start by initializing our Firebase API connection and setting two constants. N_STORIES tells us how many stories we want to load, and we’ll use LANG_API_KEY later to talk to Google’s Natural Language Processing API.</p><p>You should consider <a href="https://cloud.google.com/natural-language/docs/auth">getting your own key</a>. It’s not hard.</p><p>In the Store itself, we define 3 observables. stories is a mapping from story type to list of ids, items maps ids to their values <a href="https://github.com/HackerNews/API">HackerNews API values</a>, and alreadyListening is a set of flags that helps us avoid listening to the same stuff multiple times.</p><p>Firebase is live and all that. Once we connect, we’re going to keep getting data. Wouldn’t want to overdo it 🙂</p><p>Then we have 3 actions:</p><ol><li>listenForStories connects to Firebase on a specific story type endpoint. It listens for live updates and adds them to our state via updateItem and listenToStory</li><li>updateItem sets a specific item’s value to the API result. Later, we’ll use it for comments as well.</li><li>listenToStory connects to Firebase and starts listening for updates to a specific story.</li></ol><p>The combination of listenForStories and listenToStory ensures our list of stories re-renders in real time as the frontpage changes. Stories move up and down, upvotes accumulate, and potential title changes happen in real-time.</p><h3>App</h3><pre>// src/index.js<br><br>class App extends Component {<br>    componentDidMount() {<br>        Store.listenForStories(Store.currentRoute.key);<br>    }<br><br>    // ..<br>    <br>    renderScene({ scene }) {<br>        const { route } = scene;<br><br>        if (route.type === &#39;storylist&#39;) {<br>            return (<br>                &lt;Screen style={{paddingTop: 75}}&gt;<br>                    &lt;StoriesList storyType={route.key} /&gt;<br>                &lt;/Screen&gt;<br>            )<br>        }<br>    }<br>    <br>    // ..<br>}</pre><p>Our &lt;App&gt; component doesn’t need many changes. We make the first listenForStories call in componentDidMount, and render a &lt;StoriesList&gt; component in renderScene.</p><h3>StoriesList</h3><p>StoriesList renders a list of stories. Each shows a title, its number of likes, and how long ago it was posted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*ybWJeaI87ez48XLw.png" /></figure><pre>// src/StoriesList.js<br><br>import React from &#39;react&#39;;<br>import { observer, inject } from &#39;mobx-react&#39;;<br>import { View, ListView, Subtitle, Caption, Spinner, Row, Icon, TouchableOpacity } from &#39;@shoutem/ui&#39;;<br>import moment from &#39;moment&#39;;<br><br>const Story =<br>inject(&#39;store&#39;)(observer(function Story({ store, id }) {<br>    const item = store.items.get(id);<br><br>    if (item) {<br>        return (<br>            &lt;TouchableOpacity onPress={() =&gt; store.openStory(id)}&gt;<br>                &lt;Row&gt;<br>                    &lt;View styleName=&quot;vertical&quot;&gt;<br>                        &lt;Subtitle&gt;{item.title}&lt;/Subtitle&gt;<br>                        &lt;View styleName=&quot;horizontal space-between&quot;&gt;<br>                            &lt;Caption&gt;<br>                                &lt;Icon style={{fontSize: 15}} name=&quot;like&quot; /&gt;<br>                                {item.score}<br>                            &lt;/Caption&gt;<br>                            &lt;Caption&gt;<br>                                {moment.unix(item.time).fromNow()}<br>                            &lt;/Caption&gt;<br>                        &lt;/View&gt;<br>                    &lt;/View&gt;<br>                    &lt;Icon styleName=&quot;disclosure&quot; name=&quot;right-arrow&quot; /&gt;<br>                &lt;/Row&gt;<br>             &lt;/TouchableOpacity&gt;<br>        )<br>    }else{<br>        return (<br>            &lt;Row styleName=&quot;small&quot;&gt;<br>                &lt;Caption&gt;Loading ... ({id})&lt;/Caption&gt;<br>            &lt;/Row&gt;<br>        )<br>    }<br>}));<br><br>const StoriesList =<br>inject(&#39;store&#39;)(observer(function StoriesList ({ store, storyType }) {<br>    const stories = store.stories.get(storyType);<br><br>    if (stories) {<br>        return (<br>            &lt;ListView data={stories.slice()}<br>                      renderRow={id =&gt; &lt;Story id={id} /&gt;} /&gt;<br>        )<br>    }else{<br>        return &lt;Spinner /&gt;<br>    }<br>}));<br><br>export default StoriesList;</pre><p>Most of this code deals with rendering a nice looking Story, so I’ll breeze over the description.</p><p>We have a StoriesList, which takes our store from React Context via inject, and uses it to get a list of stories. If we have stories to show, it renders a ListView.</p><p>One thing to note in this &lt;ListView&gt; call is that we feed it stories.slice(). That’s because arrays in MobX stores are not real arrays, they’re array-like objects filled with MobX wiring. ListView doesn’t know how to handle that, so we turn them into a plain JavaScript array.</p><p>According to the creator of MobX, using .slice() is the neatest way of doing that.</p><p>The Story component renders an individual row in our list. A title, a thumbsup icon, the number of likes, how long it’s been since the story appeared.</p><p>Clicking a story calls an openStory action on our store. It loads comments.</p><h3>Loading and Filtering Comments</h3><p>Similarly to rendering a list of stories, rendering comments involves 3 steps:</p><ol><li>Add business logic to the store</li><li>Add rendering to &lt;App&gt;</li><li>Define comment components</li></ol><pre>// src/Store.js<br><br>class Store {<br>    // ...<br>    @action openStory(id) {<br>        this._navigationState.routes.push({<br>            key: String(id),<br>            id: id,<br>            type: &#39;story&#39;<br>        });<br>        this._navigationState.index += 1;<br><br>        // recursively walk through kids<br>        this.loadItem(id);<br>    }<br><br>    @action loadItem(id) {<br>        firebase.database()<br>                .ref(`v0/item/${id}`)<br>                .once(&#39;value&#39;, snapshot =&gt; {<br>                    const val = snapshot.val();<br><br>                    this.updateItem(id, val);<br>                    this.analyzeSentiment(id);<br><br>                    if (val.kids) {<br>                        val.kids.forEach(id =&gt; this.loadItem(id));<br>                    }<br>                });<br>    }<br><br>    @action analyzeSentiment(id) {<br>        const { text, sentiment } = this.items.get(id);<br><br>        if (!sentiment.fetched) {<br>            fetch(`https://language.googleapis.com/v1/documents:analyzeSentiment?key=${LANG_API_KEY}`,<br>                  {<br>                      method: &quot;POST&quot;,<br>                      headers: {<br>                          &#39;Accept&#39;: &#39;application/json&#39;,<br>                          &#39;Content-Type&#39;: &#39;application/json&#39;<br>                      },<br>                      body: JSON.stringify({<br>                          &quot;encodingType&quot;: &quot;UTF8&quot;,<br>                          &quot;document&quot;: {<br>                              &quot;type&quot;: &quot;PLAIN_TEXT&quot;,<br>                              &quot;content&quot;: text<br>                          }<br>                      })<br>                  }).then(res =&gt; res.json())<br>                    .then(json =&gt; {<br>                        this.updateSentiment(id, json);<br>                    });<br>        }<br>    }<br><br>    @action updateSentiment(id, { documentSentiment }) {<br>        if (documentSentiment) {<br>            extendObservable(this.items.get(id).sentiment, documentSentiment);<br>            this.items.get(id).sentiment.fetched = true;<br>        }<br>    }<br>}</pre><p>Comments don’t need any new state because we’re reusing the @observable items mechanism. HackerNews API puts comments and stories in the same id namespace and offers the same API endpoint to fetch individual items.</p><p>We mimic that approach.</p><p>When the openStory action is called, we push a new state to navigationState. This seamlessly updates our NavigationBar and CardStack from earlier.</p><p>Then we use loadItem to load an individual item. It connects to Firebase and fetches a story or comment, <em>once</em>. Stories can have a lot of comments and listening for live updates would keep too many open connections. Comments rarely change anyway.</p><p>When a comment is fetched, we use updateItem to save it in state, call analyzeSentiment, and walk through its list of kids to recursively load any replies.</p><p>analyzeSentiment uses a fetch call to Google Natural Language Processing to see if a comment is positive or negative. Scores range from -1.0 for most negative, to 1.0 for most positive. We’ll avoid rendering anything below 0.</p><p>Yes, that means that if a negative comment has many positive replies, those replies will be unreachable. Alas.</p><p>updateSentiment does what its name suggests. It updates the sentiment value for an existing item in our store.</p><h3>Showing Comments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*kwMDhuXLFFcOOP-h.png" /></figure><p>To render comments, and individual stories in general, we’re creating an &lt;HNItem&gt; component. It looks at the type of item it’s rendering and does the right thing. Stories are a &lt;ListView&gt; of children (comments) with a nice header, and comments are some text plus a &lt;ListView&gt; of children.</p><p>The fact that rendering nested ListViews with wanton disregard works without a hiccup, especially scrolling, is a nice surprise. Good job React Native!</p><h3>App</h3><p>But first! We add a &lt;HNItem&gt; render to our renderScene function from earlier. Its recursive nature takes care of the rest.</p><pre>// src/index.js<br><br>class App extends Component {<br>    // ...<br>    renderScene({ scene }) {<br>        const { route } = scene;<br><br>        if (route.type === &#39;storylist&#39;) {<br>            return (<br>                &lt;Screen style={{paddingTop: 75}}&gt;<br>                    &lt;StoriesList storyType={route.key} /&gt;<br>                &lt;/Screen&gt;<br>            )<br>        }else{<br>            return (<br>                &lt;Screen style={{paddingTop: 75}}&gt;<br>                    &lt;HNItem id={route.id} /&gt;<br>                &lt;/Screen&gt;<br>            );<br>        }<br>    }<br><br>    // ..<br>}</pre><h3>HNItem</h3><p>HNItem is a general component that renders any HackerNews item object. When it’s a story, it has a title with some metadata followed by a list of comments. When it’s a comment, it has text with metadata followed by a list of replies.</p><p>It looks like this:</p><pre>// src/HNItem.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { observer, inject } from &#39;mobx-react&#39;;<br>import { View, ListView, Text, Spinner } from &#39;@shoutem/ui&#39;;<br><br>import Comment from &#39;./Comment&#39;;<br>import Story from &#39;./Story&#39;;<br><br><br>const Children = observer(({ item, renderHeader = () =&gt; null }) =&gt; {<br>    if (item.kids) {<br>        return (<br>            &lt;View style={{paddingLeft: 12}}&gt;<br>                &lt;ListView data={item.kids.slice()}<br>                          renderRow={id =&gt; &lt;HNItem id={id} /&gt;}<br>                          renderHeader={renderHeader} /&gt;<br>            &lt;/View&gt;<br>        )<br>    }else{<br>        return &lt;Spinner /&gt;;<br>    }<br>});<br><br><br>const HNItem =<br>inject(&#39;store&#39;)(observer(function HNItem({ store, id }) {<br>    const item = store.items.get(id);<br><br>    if (!item || item.type === &#39;comment&#39; &amp;&amp; !item.sentiment.fetched) {<br>        return (&lt;Spinner /&gt;);<br>    }<br><br>    if (item.type === &#39;story&#39;) {<br>        return (&lt;Story item={item} /&gt;);<br>    }else if (item.type === &#39;comment&#39;) {<br>        if (item.sentiment.score &lt; 0) {<br>            return null;<br>        }else{<br>            return (&lt;Comment item={item} /&gt;);<br>        }<br>    }<br>}));<br><br>export default HNItem;<br>export { Children };</pre><p>Essentially an if with different render options.</p><p>We define a &lt;Children&gt; component in the same file because both Story and Comment use it to render their children. You can think of it as a helper component that renders a spinner until replies are loaded.</p><h3>Story</h3><p>The Story component renders a single story and its comments. We use ListView’s header feature to render a title and some metadata.</p><pre>// src/Story.js<br><br>import React from &#39;react&#39;;<br>import { Linking } from &#39;react-native&#39;;<br>import { observer } from &#39;mobx-react&#39;;<br>import { TouchableOpacity, Heading, View, Subtitle, Icon, Text } from &#39;@shoutem/ui&#39;;<br>import moment from &#39;moment&#39;;<br>import HTMLView from &#39;react-native-htmlview&#39;;<br><br>import { Children } from &#39;./HNItem&#39;;<br><br>const Story = observer(({ item }) =&gt; (<br>    &lt;View style={{paddingLeft: 14, paddingRight: 14}}&gt;<br>        &lt;Children item={item}<br>                  renderHeader={() =&gt; &lt;StoryHeader item={item} /&gt;}/&gt;<br>    &lt;/View&gt;<br>));<br><br>const StoryHeader = observer(({ item }) =&gt; (<br>    &lt;View&gt;<br>        &lt;TouchableOpacity onPress={() =&gt; Linking.openURL(item.url)}&gt;<br>            &lt;Heading&gt;{item.title}&lt;/Heading&gt;<br>        &lt;/TouchableOpacity&gt;<br><br>        &lt;View styleName=&quot;horizontal space-between&quot; style={{paddingTop: 5}}&gt;<br>            &lt;Subtitle&gt;<br>                &lt;Icon style={{fontSize: 15}} name=&quot;like&quot; /&gt;<br>                {item.score}<br>            &lt;/Subtitle&gt;<br>            &lt;Subtitle&gt;<br>                &lt;Icon style={{fontSize: 15}} name=&quot;friends&quot; /&gt;<br>                {item.by}<br>            &lt;/Subtitle&gt;<br>            &lt;Subtitle&gt;<br>                {moment.unix(item.time).fromNow()}<br>            &lt;/Subtitle&gt;<br>        &lt;/View&gt;<br><br>        {item.text ? &lt;StoryText item={item} /&gt; : null}<br>    &lt;/View&gt;<br>));<br><br>const StoryText = observer(({ item }) =&gt; (<br>    &lt;HTMLView value={item.text} style={{paddingBottom: 10, paddingTop: 5}} addLineBreaks={false} /&gt;<br>));<br><br>export default Story;</pre><p>The interesting part here is HTMLView. We use it to render any text a story might have – mostly seen in “Ask HN” submissions.</p><p>The component comes from James Friend’s <a href="https://github.com/jsdf/react-native-htmlview">react-native-htmlview</a> which takes HTML and renders it as a tree of React Native &lt;Text&gt; components. This is useful because unlike on the web, you don’t get automatic HTML rendering in apps.</p><p>Guess what HackerNews comments and story texts are? Yep, HTML.</p><h3>Comment</h3><p>An individual comment is similar to a story. It renders itself, then a list of its children.</p><p>The main difference between a comment and a story is that comments have a “Show Replies” button. It toggles replies on and off, which makes the comment feed easier to read.</p><p>We use local state for that. No need to bother our MobX store with things that are this localized. Other components don’t care about a specific comment’s replies being on or off.</p><pre>// src/Comment.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { observer, inject } from &#39;mobx-react&#39;;<br>import { TouchableOpacity, View, Caption, Icon, Text } from &#39;@shoutem/ui&#39;;<br>import moment from &#39;moment&#39;;<br>import HTMLView from &#39;react-native-htmlview&#39;;<br><br>import { Children } from &#39;./HNItem&#39;;<br><br>const ChildrenToggle = observer(({ item, showChildren, onPress }) =&gt; (<br>    &lt;TouchableOpacity onPress={onPress}&gt;<br>        &lt;View styleName=&quot;horizontal h-end&quot;&gt;<br>            &lt;Caption&gt;<br>                &lt;Icon style={{fontSize: 12, paddingRight: 5}} name=&quot;comment&quot; /&gt;<br>                {item.kids.length} {item.kids.length &gt; 1 ? &#39;replies&#39; : &#39;reply&#39;}<br>                &lt;Icon style={{fontSize: 8}} name={showChildren ? &#39;down-arrow&#39; : &#39;right-arrow&#39;}  /&gt;<br>            &lt;/Caption&gt;<br>        &lt;/View&gt;<br>    &lt;/TouchableOpacity&gt;<br>));<br><br>@observer @inject(&#39;store&#39;)<br>class Comment extends Component {<br>    state = {<br>        showChildren: false<br>    }<br><br>    toggleChildren = () =&gt; this.setState({<br>        showChildren: !this.state.showChildren<br>    });<br><br>    render() {<br>        const { item, store } = this.props,<br>              { showChildren, expanded } = this.state;<br>        let { kids = [] } = item;<br><br>        return (<br>            &lt;View style={{paddingBottom: 20}}&gt;<br>                &lt;View styleName=&quot;horizontal space-between&quot; style={{paddingTop: 5}}&gt;<br>                    &lt;Caption&gt;<br>                        &lt;Icon style={{fontSize: 15}} name=&quot;friends&quot; /&gt;<br>                        {item.by}<br>                    &lt;/Caption&gt;<br>                    &lt;Caption&gt;<br>                        {moment.unix(item.time).fromNow()}<br>                    &lt;/Caption&gt;<br>                    &lt;Caption&gt;<br>                        {item.sentiment.score &gt; 0 ? &#39;positive&#39; : &#39;neutral&#39;}<br>                    &lt;/Caption&gt;<br>                &lt;/View&gt;<br><br>                &lt;HTMLView value={item.text} paragraphBreak={&#39;\n&#39;} lineBreak={null} /&gt;<br><br>                {kids.length ? &lt;ChildrenToggle item={item} showChildren={showChildren} onPress={this.toggleChildren} /&gt; : null}<br><br>                {showChildren ? &lt;Children item={item} /&gt; : null}<br>            &lt;/View&gt;<br>        );<br>    }<br>};<br><br>export default Comment;</pre><p>We use ToggleChildren as a helper component to make our code more readable, use a bunch of Views and Captions to render meta data, HTMLView to render the comment itself, and the &lt;Children&gt; component from before to optionally render replies.</p><h3>Voila</h3><p>A neat little HackerNews app where people are nice. You’re welcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*uTkTfztLyYdPpODfJUvReQ.gif" /></figure><p>Now how do I publish it on the App Store?</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/react-native-hackernews-app/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b591aca86727" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/tutorial-build-a-react-native-hackernews-app-where-people-are-nice-b591aca86727">Tutorial: Build a React Native HackerNews app where people are nice</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Build a real-time visualization app of Bitcoin transactions]]></title>
            <link>https://medium.com/react-native-development/tutorial-build-a-real-time-visualization-app-of-bitcoin-transactions-5be1bda7708b?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/5be1bda7708b</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Mon, 24 Jul 2017 15:12:09 GMT</pubDate>
            <atom:updated>2017-07-24T13:31:49.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wanted to build a data visualization with livestreaming real-time data? You’re in luck! That’s what this tutorial is about 🙂</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FkCLaRgFi0wg%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DkCLaRgFi0wg&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FkCLaRgFi0wg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aee56ab90b7e7f19fb80608636ac360c/href">https://medium.com/media/aee56ab90b7e7f19fb80608636ac360c/href</a></iframe><p>We’re building an app that shows the real-time value of Bitcoin, Etherum, and Litecoin as judged by the <a href="https://www.gdax.com/">Coinbase GDAX</a> exchange. We’ll connect with a Websocket, listen for transaction messages, and draw a pretty picture with some jumping numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*XeneqREsVnxEm1Ww.gif" /><figcaption>Real-time visualization app of Bitcoin transactions</figcaption></figure><p>The app updates every time a new trade occurs on GDAX and shows transaction volume per every 3-second interval. It looked good when I was testing. For a super correct approach, you’d want to adjust window size to traffic flow. Longer window when fewer messages, shorter when more.</p><p>Then again, you’d also have to consume multiple exchanges to get the really real value of a coin.</p><p><strong>Here’s what you’ll learn today:</strong></p><ul><li>how to use Websockets in React Native</li><li>the basics of React Native SVG</li><li>how to use a d3.stack to make stream graphs</li></ul><p>You will also exercise your skills with <strong>Redux</strong>, <strong>Shoutem UI Toolkit</strong>, and <strong>Functional Programming</strong>. Don’t worry if you don’t know them super well. I’ll explain everything.</p><p>You should <a href="http://eepurl.com/cxTnOL">subscribe by email</a> and join 1,622 coders who get a new React Native app in their inbox twice a month.</p><p>We’re building our app in 4 stages: Setup and boilerplate, consuming data from GDAX, drawing our live graph, showing some metadata.</p><p>If you follow along with copypaste, you can build this in about 10 minutes. It took me ~8 hours to build from scratch. ☕️</p><p>You can see the <a href="https://github.com/shoutem/school/tree/master/CryptoDataVizApp">full source on Github</a>.</p><p>Here we go →</p><h3>Step 0: Setup and boilerplate</h3><p>We start by initializing our app and installing dependencies. We’re using React Native 0.43 so that we can use Shoutem UI Toolkit. It’s a quick way to make a pretty app.</p><pre>$ react-native init CryptoVizDataApp --version react-native@0.43.3<br>$ npm install --save @shoutem/ui better-fetch d3 react-native-svg@4.5.0<br>$ npm install --save lodash.frompairs lodash.groupby lodash.last lodash.takeright<br>$ npm install --save redux redux-logger redux-thunk<br>$ react-native link<br>$ cd CryptoVizDataApp<br>$ mkdir src</pre><p>Running those commands creates a new default React Native app with all of the dependencies we’ll need in this tutorial. Yes, it would’ve been easier to install all of lodash, but it’s big, and we only need 4 functions.</p><p>Go into index.ios.js or index.android.js depending on which platform you want to develop for. Update the CryptoVizDataApp component to look like this:</p><pre>// index.ios.js<br>import App from &#39;./src&#39;;<br><br>export default class CryptoDataVizApp extends Component {<br>  render() {<br>    return (<br>      &lt;App /&gt;<br>    );<br>  }<br>}</pre><p>I like to make my own App component and render it in index. Makes it easy to share the same app between both platforms.</p><h3>App boilerplate</h3><p>Your simulator should be crying about missing files and components right now. It’s a common theme throughout this tutorial. You’re meant to have a working app at the end of every step 🙂</p><p>We define our App component in src/index.js and add some Redux boilerplate to initiate a data store.</p><pre>// src/index.js<br><br>import { Screen, Divider } from &#39;@shoutem/ui&#39;;<br>import { createStore, applyMiddleware } from &#39;redux&#39;;<br>import thunkMiddleware from &#39;redux-thunk&#39;;<br>import { createLogger } from &#39;redux-logger&#39;;<br>import { Provider, connect } from &#39;react-redux&#39;;<br><br>import rootReducer from &#39;./reducer&#39;;<br>import { initData } from &#39;./actions&#39;;<br>// you should import these later<br>import CurrentValue from &#39;./CurrentValue&#39;;<br>import TransactionVolumeGraph from &#39;./TransactionVolumeGraph&#39;;<br>import Description from &#39;./Description&#39;;<br><br>const store = createStore(<br>    rootReducer,<br>    applyMiddleware(<br>        thunkMiddleware,<br>        createLogger()<br>    )<br>);<br><br>class App extends Component {<br>    componentDidMount() {<br>        const { dispatch } = this.props;<br><br>        dispatch(initData());<br>    }<br><br>    render() {<br>        return (<br>            &lt;Screen&gt;<br>                // you should add these later<br>                &lt;Divider /&gt;<br>                &lt;CurrentValue /&gt;<br>                &lt;Divider /&gt;<br>                &lt;Divider /&gt;<br>                &lt;TransactionVolumeGraph /&gt;<br>                &lt;Divider /&gt;<br>                &lt;Description /&gt;<br>            &lt;/Screen&gt;<br>        )<br>    }<br>}<br><br>const ConnectedApp = connect(state =&gt; state)(App);<br><br>export default () =&gt; (<br>    &lt;Provider store={store}&gt;<br>        &lt;ConnectedApp /&gt;<br>    &lt;/Provider&gt;<br>)I suggest copypasting this code without the individual components. Add them during steps 2 and 3 so you can see what you’re doing. They’re included here for completeness.</pre><p>Let’s walk through the important parts of this code.</p><p>rootReducer is going to be our <a href="http://redux.js.org/docs/basics/Reducers.html">Redux Reducer</a>. It defines the shape of our global data store.</p><p>initData is a <a href="https://github.com/gaearon/redux-thunk">Redux Thunk</a> that initiates the dataflow our app relies on. It fetches some info from GDAX and dispatches some actions. You’ll see in Step 1.</p><p>We initiate a Redux Store with createStore and setup an App component that renders our UI and dispatches initData when it renders.</p><p>ConnectedApp is a helper component with access to our Redux Store via connect().</p><p>In the end, we export a component that renders a <a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store">Redux Provider</a> and our ConnectedApp.</p><h3>Redux boilerplate</h3><p>Most of our Redux boilerplate went into creating a data store and giving our App access. What’s left is a default reducer that doesn’t do anything yet.</p><pre>// src/reducer.js<br>import { combineReducers } from &#39;redux&#39;;<br>import fromPairs from &#39;lodash.frompairs&#39;;<br>import takeRight from &#39;lodash.takeright&#39;;<br><br>const prices = (state = {}, action) =&gt; {<br>    switch (action.type) {<br>        default:<br>            return state;<br>    }<br>};<br><br>const rootReducer = combineReducers({<br>    prices<br>});<br><br>export default rootReducer;</pre><p>We aren’t using fromPairs and takeRight just yet, but you should import them anyway. I promise we’ll use them later.</p><p>Our reducer is going to hold data of this shape:</p><pre>{ prices: {<br>    &#39;BTC-USD&#39;: {<br>        id: &#39;BTC-USD&#39;,<br>        display_name: &#39;BTC/USD&#39;,<br>        values: [{time: Time, price: 2345}, {time: Time, 2344}, ..]<br>    },<br>    // ...<br>}}</pre><p>It’s not obvious from the blank reducer, I know. That’s because I wanted to read the list of available products from GDAX and avoid making assumptions. You’ll see this decision complicating other parts of the codebase, too.</p><p>Using combineReducers isn’t necessary when you have a single reducer like this, but I find it often comes in handy when you decide to expand.</p><p>If you create an empty src/actions.js file, errors should go away, and you’ll see a blank app.</p><h3>Step 1: Consuming data from GDAX</h3><p>GDAX offers a <a href="https://docs.gdax.com/#websocket-feed">Websocket Feed API</a> that gives us live access to every trade. We can use their match message type to assess the current price of coins and measure transaction volume.</p><p>According to the docs, a match message means “A trade occurred between two orders”. I’m new to exchange lingo, but I think that means coins and money exchanged hands.</p><p>Messages look like this:</p><pre>{<br>    &quot;type&quot;: &quot;match&quot;,<br>    &quot;trade_id&quot;: 10,<br>    &quot;sequence&quot;: 50,<br>    &quot;maker_order_id&quot;: &quot;ac928c66-ca53-498f-9c13-a110027a60e8&quot;,<br>    &quot;taker_order_id&quot;: &quot;132fb6ae-456b-4654-b4e0-d681ac05cea1&quot;,<br>    &quot;time&quot;: &quot;2014-11-07T08:19:27.028459Z&quot;,<br>    &quot;product_id&quot;: &quot;BTC-USD&quot;,<br>    &quot;size&quot;: &quot;5.23512&quot;,<br>    &quot;price&quot;: &quot;400.23&quot;,<br>    &quot;side&quot;: &quot;sell&quot;<br>}</pre><p>We’re interested in the product_id and price. We’ll make our own timestamps. GDAX’s sometimes don’t make sense and break our graph. Possibly due to delayed messages.</p><p>Consuming data happens in Redux actions, src/actions.js.</p><h3>initData</h3><p>As mentioned earlier, initData connects to the firehose and gets our app going.</p><pre>// src/actions.js<br>import fetch from &#39;better-fetch&#39;;<br><br>const URL = &quot;https://api-public.sandbox.gdax.com/&quot;,<br>      SOCKET_URL = &quot;wss://ws-feed.gdax.com&quot;<br><br>export const initData = () =&gt; {<br>    return function (dispatch) {<br>        fetch(`${URL}products`)<br>          .then(fetch.throwErrors)<br>          .then(res =&gt; res.json())<br>          .then(json =&gt; {<br>              dispatch(setProducts(json));<br>              dispatch(connectSocket());<br>          })<br>          .catch(e =&gt; console.error(e.message));<br>    };<br>}</pre><p>We’re using my <a href="https://github.com/Swizec/better-fetch">better-fetch</a> wrapper to make fetch() a little easier to use.</p><p>We start by fetching a list of products from <a href="https://api-public.sandbox.gdax.com/products.">https://api-public.sandbox.gdax.com/products.</a></p><p>When we get our list, we dispatch two actions: A setter action setProducts and a rich thunk connectSocket that initiates the websocket firehose.</p><h3>connectSocket</h3><pre>// src/actions.js<br><br>export const connectSocket = () =&gt; {<br>    const ws = new WebSocket(SOCKET_URL);<br><br>    return function (dispatch, getState) {<br>        ws.onopen = () =&gt; {<br>            const state = getState(),<br>                  product_ids = Object.keys(state.prices)<br>                                      .map(k =&gt; state.prices[k].id);<br><br>            ws.send(JSON.stringify({<br>                type: &#39;subscribe&#39;,<br>                product_ids<br>            }));<br>        }<br><br>        ws.onmessage = (msg) =&gt; {<br>            const { type, price, product_id, reason, size } = JSON.parse(msg.data);<br>            const value = {<br>                time: new Date(),<br>                price: Number(price)<br>            }<br><br>            if (type === &#39;match&#39; &amp;&amp; price) {<br>                dispatch(addValue(product_id, value));<br>            }<br>        }<br><br>        ws.onerror = (e) =&gt; {<br>            console.log(e.message);<br>        }<br><br>        ws.onclose = (e) =&gt; {<br>            console.log(e.code, e.reason);<br>        }<br>    }<br>}</pre><p>Websocket is a magic global object provided by React Native. It lets us <a href="https://facebook.github.io/react-native/docs/network.html">connect to websockets</a> just like you would on the web.</p><p>A socket opens a persistent connection between our app and a server. In this case, we connect to the GDAX exchange.</p><p>When our socket connects, it calls the onopen callback. We tell GDAX we’d like to receive messages about certain products by sending a type: &#39;subscribe&#39; message and a list of product ids.</p><p>GDAX then starts sending us messages in real-time.</p><p>Each time we get one, our onmessage callback is triggered. In it, we parse the message, extract relevant data, and dispatch the addValue setter action.</p><h3>setter actions</h3><p>Two setter actions support our big thunks. Setting a list of products, and adding individual values to the list.</p><pre>// src/actions.js<br><br>export const setProducts = (products) =&gt; ({<br>    type: &#39;SET_PRODUCTS&#39;,<br>    products: products.filter(({ quote_currency }) =&gt; quote_currency === &#39;USD&#39;)<br>});<br><br>export const addValue = (product, value) =&gt; ({<br>    type: &#39;ADD_VALUE&#39;,<br>    product,<br>    value<br>});</pre><p>Both setProducts and addValue are actions that have a type and some data. Our reducer uses these to generate the next iteration of our state.</p><h3>reducer</h3><p>With our actions in place, it’s time to spruce up the blank reducer we made earlier.</p><pre>// src/reducer.js<br><br>const prices = (state = {}, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;SET_PRODUCTS&#39;:<br>            return Object.assign({}, state, fromPairs(<br>                action.products.map(({ id, base_currency, display_name }) =&gt; [<br>                    id,<br>                    {<br>                        id,<br>                        display_name,<br>                        base_currency,<br>                        values: []<br>                    }<br>                ])));<br>        case &#39;ADD_VALUE&#39;:<br>            const { product, value } = action;<br><br>            let values = state[product].values.concat(value);<br><br>            if (values.length &gt; 500) {<br>                values = takeRight(values, 500);<br>            }<br><br>            return Object.assign({}, state, {<br>                [product]: Object.assign({}, state[product], {<br>                    values: values<br>                })<br>            });<br>        default:<br>            return state;<br>    }<br>};</pre><p>There’s tricky stuff going on here. Mostly due to the fact that we really should have had a separate reducer for each product. Oops.</p><p>SET_PRODUCTS is okay. We create a new copy of state with Object.assign and merge it with a dictionary of products. We use Lodash’s fromPairs to make the dictionary out of a list of key value pairs.</p><p>ADD_VALUE is kind of hard to read. We’re still making a new copy of state, but this time we merge it with a single-key dictionary to overwrite a specific product.</p><p>Said product is a copy of itself via Object.assign, merged with a new list of values.</p><p>We also use this opportunity to limit our list of values to 500 members using takeRight.</p><p>If all went well, you should see a bunch of Redux activity in your logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hsB_n0-5t1bowL8z.png" /><figcaption>Redux activity logs</figcaption></figure><h3>Step 2: Draw a live Streamgraph with D3 and Svg</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*9p0blHxXPtQ-HUIA.png" /><figcaption>D3.stack and react-native-svg are used to draw a stream graph of Bitcoin transaction volume.</figcaption></figure><p>We’re using a combination of <a href="https://github.com/d3/d3-shape/blob/master/README.md#stacks">D3.stack</a> and <a href="https://github.com/react-native-community/react-native-svg">react-native-svg</a> to draw a stream graph of transaction volume.</p><p>D3 gives us shape generators and generally calculates everything for us. react-native-svg gives us SVG in React Native, a way to draw vector graphics.</p><p>I wasn’t able to figure out what react-native-svg uses under the hood. I suspect it’s real SVG or Native components of some sort. Whatever it does, it works great.</p><p>You’ll barely notice you’re not on the web! No D3 axis generators, though</p><p>Our graph comes in two components: A smart TransactionVolumeGraph and a presentational StreamGraph.</p><h3>TransactionVolumeGraph</h3><p>TransactionVolumeGraph has a few jobs. It connects to our Redux store, renders the Svg, calculates appropriate width and height, and feeds data into StreamGraph.</p><pre>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { Dimensions } from &#39;react-native&#39;;<br>import Svg from &#39;react-native-svg&#39;;<br><br>import StreamGraph from &#39;./StreamGraph&#39;;<br>import { chartValues } from &#39;./helpers&#39;;<br><br><br>const TransactionVolumeGraph = connect(state =&gt; state)(<br>    ({ prices }) =&gt; {<br>        const { height, width } = Dimensions.get(&#39;window&#39;);<br>        const values = chartValues(prices);<br><br>        return (<br>            &lt;Svg height={height/2} width={width}&gt;<br>                &lt;StreamGraph keys={Object.keys(prices)}<br>                             values={values}<br>                             width={width}<br>                             height={height/2} /&gt;<br>            &lt;/Svg&gt;<br>        );<br>    }<br>);<br><br>export default TransactionVolumeGraph;</pre><p>We’re using React Native’s <a href="https://facebook.github.io/react-native/docs/dimensions.html">Dimensions API</a> to get screen width and height and a chartValues helper method to calculate values to feed into our graph.</p><h3>chartValues</h3><p>chartValues is a tricky function. It was one of the most time consuming parts of this project.</p><p>Its job is to take our data, chunk it into 3-second pieces, size each chunk, and return a list of product-volume objects like this:</p><pre>[<br>    {time: 12345, &#39;BTC-USD&#39;: 3, &#39;ETH-USD&#39;: 2, &#39;LTC-USD&#39;: 10},<br>    {time: 12348, &#39;BTC-USD&#39;: 1, &#39;ETH-USD&#39;: 5, &#39;LTC-USD&#39;: 0},<br>    // ...<br>]</pre><p>d3.stack knows how to take data of that shape and turn it into a streamgraph.</p><p>Here’s how we convert data from our state to something d3.stack can read:</p><pre>// src/helpers.js<br><br>import fromPairs from &#39;lodash.frompairs&#39;;<br>import groupBy from &#39;lodash.groupby&#39;;<br>import last from &#39;lodash.last&#39;;<br>import * as d3 from &#39;d3&#39;;<br><br>function chartValues(prices)<br>{<br>    const products = Object.values(prices),<br>          keys = Object.keys(prices);<br><br>    if (!products.length) {<br>        return [];<br>    }<br><br>    const chunked = fromPairs(products.map(({ id, values }) =&gt;<br>        [id,<br>         groupBy(values, val =&gt; {<br>             // round to 3 second accuracy<br>             const t = val.time.getTime();<br>             return Math.round(t/3000)*3000;<br>         })<br>        ]<br>    ));<br><br>    let [t0, t1] = d3.extent(<br>        Object.values(chunked)<br>              .reduce((arr, p) =&gt; arr.concat(Object.keys(p)), [])<br>              .map(t =&gt; new Date(Number(t)))<br>    );<br><br>    return d3.timeSeconds(t0, t1, 3)<br>             .map(t =&gt; fromPairs(<br>                 Object.keys(chunked)<br>                       .map(k =&gt; [k, (chunked[k][t.getTime()] || []).length])<br>                       .concat([[&#39;time&#39;, t]])<br>             ))<br>}<br><br>export { chartValues };</pre><p>See, I wasn’t kidding</p><p>The conversion happens in 3 steps:</p><ol><li>Go through products and their values, and use lodash groupBy to turn them into groups based on timestamp</li><li>Use d3.extent to find the oldest and latest timestamp in the data. Timestamps are group names from step 1.</li><li>Create an iterator from t0 to t1 with a 3 second step, build array of objects</li></ol><h3>StreamGraph</h3><p>Once we have our data in the right format, building our StreamGraph is just a matter of combining a few different D3 tutorials and examples. Everyone writes D3 that way.</p><p>To make our lives easier, we’re assuming JavaScript is super fast so we regenerate the whole graph on every update. Including all the D3 objects that build it. This is not very efficient, but it works well enough</p><pre>// src/StreamGraph.js<br><br>import React from &#39;react&#39;;<br>import { G, Path } from &#39;react-native-svg&#39;;<br>import * as d3 from &#39;d3&#39;;<br><br>const StreamGraph = ({ keys, values, width, height }) =&gt; {<br>    const stack = d3.stack()<br>                    .keys(keys)<br>                    .order(d3.stackOrderNone)<br>                    .offset(d3.stackOffsetSilhouette),<br>          series = stack(values);<br><br>    if (!series.length) {<br>        return null;<br>    }<br><br>    const colors = d3.schemeCategory20c,<br>          y = d3.scaleLinear()<br>                .domain([<br>                    d3.min(series[0].map(([y0, y1]) =&gt; y0)),<br>                    d3.max(series[series.length-1].map(([y0, y1]) =&gt; y1))<br>                ])<br>                .range([0, height]),<br>          x = d3.scaleLinear()<br>                .domain(d3.extent(values.map(v =&gt; v.time)))<br>                .range([0, width]);<br><br>    const area = d3.area()<br>                   .y0(([y0, y1]) =&gt; y(y0))<br>                   .y1(([y0, y1]) =&gt; y(y1))<br>                   .x(({ data }) =&gt; x(data.time));<br><br>    return (<br>        &lt;G&gt;<br>            {series.map((s, i) =&gt; area(s)<br>                    ? &lt;Path d={area(s)}<br>                            fill={colors[8+i]}<br>                            key={keys[i]} /&gt;<br>                    : null<br>            )}<br>        &lt;/G&gt;<br>    );<br>};<br><br>export default StreamGraph;</pre><p>A few D3 features come together to build our stream graph.</p><p>We create a d3.stack generator, tell it which keys to look for in each datapoint, to avoid any ordering, and to arrange our data in a silhouette. Then we use it to create a series.</p><p>This creates data perfectly suited to feed into an area generator. Each data point has coordinates with ys set up so values with the same x stack one on top of the other.</p><p>Then we create two linear scales, x and y, that will help us translate our data values to our drawing values. x maps timestamps in our dataset to horizontal UI coordinates. y maps values to vertical coordinates.</p><p>Using our x and y scales, we create an area generator and tell it how to use our scales via the y0, y1, and x value accessors. Now we can feed entries from our series into area to generate SVG shapes.</p><p>To render our Streamgraph, we use a &lt;G&gt; grouping element, and fill it with a stream of &lt;Path&gt;s. Each path’s d attribute, which defines its shape, comes from our area generator.</p><p>We use one of D3’s default color schemes to color our graph. schemeCategory20c with an offset of 8 gives us shades of green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*ZKvNwRXv49Zd2kEo.png" /></figure><p>You should now see a Streamgraph. It might take a few seconds to show up.</p><h3>Step 3: Show live prices</h3><p>Our Streamgraph looks good, but it doesn’t say much. We should add some descriptive text.</p><p>We’ll add a component showing CurrentValue and a component with some Description. Nothing fancy, just some styled text using Shoutem UI default styles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*Jt3YV3yxdVJ7F6PM.png" /><figcaption>Live prices and Bitcoin transactions volume</figcaption></figure><h3>CurrentValue</h3><p>In theory, the current value of any cryptocoin is the price of the last successful transaction. That means we have to look at our Redux store and fetch the last known value for each coin.</p><p>Like this:</p><pre>import React from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { View, Subtitle, Heading, Text } from &#39;@shoutem/ui&#39;;<br>import last from &#39;lodash.last&#39;;<br><br>import { lastValueOrZero } from &#39;./helpers&#39;;<br><br>const CurrentValue = connect(state =&gt; ({<br>    sum: Object.values(state.prices)<br>               .map(({ values }) =&gt; last(values) || {price: 0})<br>               .reduce((sum, { price }) =&gt; sum+price, 0),<br>    btc: lastValueOrZero(state.prices[&#39;BTC-USD&#39;]),<br>    eth: lastValueOrZero(state.prices[&#39;ETH-USD&#39;]),<br>    ltc: lastValueOrZero(state.prices[&#39;LTC-USD&#39;])<br>}))(({ sum, btc, eth, ltc }) =&gt; (<br>    &lt;View&gt;<br>        &lt;Subtitle styleName=&quot;h-center&quot;&gt;Current Crypto Value&lt;/Subtitle&gt;<br>        &lt;Heading styleName=&quot;h-center&quot; style={{paddingTop: 10}}&gt;<br>            ${sum.toFixed(2)}<br>        &lt;/Heading&gt;<br>        &lt;View styleName=&quot;horizontal h-center space-between&quot; style={{paddingLeft: 20,<br>                                                                   paddingRight: 20}}&gt;<br>            &lt;Text&gt;BTC: ${btc.price.toFixed(2)}&lt;/Text&gt;<br>            &lt;Text&gt;ETH: ${eth.price.toFixed(2)}&lt;/Text&gt;<br>            &lt;Text&gt;LTC: ${ltc.price.toFixed(2)}&lt;/Text&gt;<br>        &lt;/View&gt;<br>    &lt;/View&gt;<br>));<br><br>export default CurrentValue;</pre><p>We use the map-state-to-props function in our Redux connect() call to do the heavy lifting. It builds a sum of last known values, and a list of last known values for each coin.</p><p>Because JavaScript doesn’t have a maybe monad, we have to get creative. Some values don’t exist when we first try to read them.</p><pre>// src/helpers.js<br>function lastValueOrZero(prices) {<br>    return last(({ values = [] } = prices || {}).values) || {price: 0};<br>}</pre><p>People on the internet say this is easy for them to read, but I think they’re lying. It almost broke my brain coming up with it.</p><h3>Swizec on Twitter</h3><p>On the scale of 1 to Eldritch horror, how bad is this code?</p><h3>Luke Edwards on Twitter</h3><p>@Swizec nothing is awful unless you think it is 👍 that said, your last 3 keys would benefit from an utility function since they&#39;re really the same~</p><p>The reason it’s a one liner is because I wanted to include it directly in the map-state-to-props function at first. The logic goes like this:</p><ul><li>take prices or empty object, {}</li><li>deconstruct values out of it, use [] by default</li><li>take the last() value, or {price: 0} by default</li></ul><p>Can you imagine the if chain for that? It’s almost better as a one-liner…</p><p>When we have those props, we render them as text. That part is easy 🙂</p><h3>Description</h3><p>Compared to CurrentValue, Description is a walk in the park. It shows the average, minimum, and maximum number of transactions per every 3 second period.</p><pre>// src/Description.js<br><br>import React from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { View, Text, Divider, Subtitle } from &#39;@shoutem/ui&#39;;<br>import * as d3 from &#39;d3&#39;;<br><br>import { chartValues } from &#39;./helpers&#39;;<br><br>const Description = connect(state =&gt; ({<br>    times: Object.values(state.prices)<br>                 .reduce((arr, { values }) =&gt; arr.concat(values), [])<br>                 .map(({ time }) =&gt; time),<br>    prices: state.prices<br>}))(({ times, prices }) =&gt; {<br>    const [start, end] = d3.extent(times);<br><br>    if (!start) {<br>        return (<br>            &lt;View styleName=&quot;horizontal h-center&quot;&gt;<br>                &lt;Text&gt;Waiting for data&lt;/Text&gt;<br>            &lt;/View&gt;<br>        );<br>    }<br><br>    const counts = chartValues(prices).map(value =&gt; {<br>        const keys = Object.keys(value).filter(k =&gt; k !== &#39;time&#39;);<br>        return keys.reduce((sum, k) =&gt; sum+value[k], 0);<br>    });<br><br>    const format = d3.timeFormat(&#39;%I:%M:%S&#39;);<br><br><br>    return (<br>        &lt;View styleName=&quot;vertical h-center&quot;&gt;<br>            &lt;Text&gt;Transaction volume since&lt;/Text&gt;<br>            &lt;Subtitle&gt;{format(start)}&lt;/Subtitle&gt;<br>            &lt;Divider /&gt;<br>            &lt;Text&gt;Average &lt;Subtitle&gt;{(d3.mean(counts) || 0).toFixed(1)}&lt;/Subtitle&gt; every 3 seconds&lt;/Text&gt;<br>            &lt;View styleName=&quot;horizontal h-center space-between&quot;&gt;<br>                &lt;Text style={{paddingLeft: 5, paddingRight: 5}}&gt;<br>                    Min: &lt;Subtitle&gt;{d3.min(counts)}&lt;/Subtitle&gt;<br>                &lt;/Text&gt;<br>                &lt;Text style={{paddingLeft: 5, paddingRight: 5}}&gt;<br>                    Max: &lt;Subtitle&gt;{d3.max(counts)}&lt;/Subtitle&gt;<br>                &lt;/Text&gt;<br>            &lt;/View&gt;<br>        &lt;/View&gt;<br>    )<br>});<br><br>export default Description;</pre><p>If it’s a cakewalk, why is it longer?</p><p>Well, we get a list of all times in our data and use it to extract the start time. We show that as <em>“Volume since X”</em> so users don’t feel lost in time too much.</p><p>We use chartValues again to calculate volumes for our dataset and turn it into a flat list of volumes with a .map. Yes, calling chartValues again in this component is inefficient.</p><p>It’s okay. Phones are fast.</p><p>In the render output, we use d3.mean, d3.min, and d3.max to get appropriate values from our list of volumes. A d3.format helps us format the timestamp.</p><h3>Voilá</h3><p>If all went well, you should have an app that shows you live-updating current prices of Bitcoin, Etherum, and Litecoin, and their current transaction volume on GDAX. If it didn’t, I suggest checking the <a href="https://github.com/shoutem/school/tree/master/CryptoDataVizApp">source on Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*OBFHFapeCunIP43o.gif" /><figcaption>An app with prices of Bitcoin, Etherum, and Litecoin.</figcaption></figure><p>I think it’s neat</p><p><a href="http://eepurl.com/cxTnOL">Subscribe by email</a> to get the next React Native tutorial 2 weeks from now.</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/tutorial-bitcoin-transactions-react-native/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be1bda7708b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/tutorial-build-a-real-time-visualization-app-of-bitcoin-transactions-5be1bda7708b">Tutorial: Build a real-time visualization app of Bitcoin transactions</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Build a crowdsourced react native Travel App with react-navigation, AsyncStorage, and…]]></title>
            <link>https://medium.com/react-native-development/tutorial-build-a-crowdsourced-react-native-travel-app-with-react-navigation-asyncstorage-and-385304f7b431?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/385304f7b431</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Tue, 27 Jun 2017 15:21:45 GMT</pubDate>
            <atom:updated>2017-06-27T07:34:09.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tutorial: Build a crowdsourced react native Travel App with react-navigation, AsyncStorage, and Firebase</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FiMt4Xdsafvw%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DiMt4Xdsafvw&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FiMt4Xdsafvw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/873e59404552a400e3679d0e1f929ef3/href">https://medium.com/media/873e59404552a400e3679d0e1f929ef3/href</a></iframe><p>For this week’s React Native app build, I wanted to play with react-navigation. It’s the new official way to build navigation in react native apps.</p><p>We’re building a Crowdsourced Travel App. You say where you’re going, the app suggests what to pack.</p><p>Keep forgetting your toothbrush? Now you won’t. Don’t know what to pack for a hike in the tropics? Now you know.</p><p>Things you’ve packed save into local AsyncStorage, recommendations are crowdsourced through Firebase. Any time someone adds an item, it’s a recommendation for all. Beautiful thumbnails come from Flickr.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*9Gav9tl7EMmd2Mq7.gif" /></figure><p><strong>Here’s what you’ll learn today:</strong></p><p>— react-navigation for managing app screens</p><p>— AsyncStorage for data persistence</p><p>— a simple Firebase integration</p><p>— using Dimensions to help with styling</p><p>We’re going to pillage Flickr integration from my Music App Tutorial, I’ll breeze through the explanation here, and I assume you have Firebase itself set up. Follow instructions in my <a href="https://school.shoutem.com/lectures/chat-app-firebase-redux-react-native/">Chat App Tutorial</a> to set up your account.</p><p><strong>Dependencies:</strong></p><p>Before we begin, here’s what you should install.</p><pre>$ react-native init TravelApp<br>$ npm install --save querystring firebase react-navigation<br>$ react-native link</pre><p>We’re using querystring inside our Flickr component to compose URLs, firebase talks to Firebase, and react-navigation handles our navigation needs.</p><p>There is now Redux or MobX for this build because I wanted to keep it simple. Towards the end I started regretting this decision, but not badly enough to rewrite 🙂</p><p><strong>Full code</strong></p><p>This tutorial focuses on the interesting bits. Should anything seem confusing or like it doesn’t fit together. You should head to the <a href="https://github.com/shoutem/school/tree/master/TravelApp">full code on Github</a>.</p><p>You should be able to clone that repo, npm install, and react-native run-ios to see a working app.</p><p>If you think you’d enjoy receiving a new React Native app tutorial every 2 weeks, you should consider <a href="http://eepurl.com/cxTnOL">subscribing by email</a>. Join 1,500+ coders receiving every build.</p><h3>Wire up react-navigation</h3><p><a href="https://reactnavigation.org/">react-navigation</a> gives us a simple way to build navigation between different screens into our app. It offers a <a href="https://reactnavigation.org/docs/navigators/stack">stack approach</a>, where screens stack one on top of the other, a <a href="https://reactnavigation.org/docs/navigators/tab">tab approach</a>, where a screen is built with tabs, and a <a href="https://reactnavigation.org/docs/navigators/drawer">drawer approach</a>, where you have a menu on the side.</p><p>We’re using stacks and tabs. Stack for the overall <em>“Where are you going?”</em> navigation, and tabs to organize our packing lists into categories.</p><p>What I like about React Navigation is that your screens don’t have to think about navigation. Don’t even need to be aware of it. Set up and forget. Build your views like you always have.</p><p>When you do need to know what screen path you’re on, you can look at this.props.navigation to find out. Useful when you have to fetch specific data or something.</p><p>Internally React Navigation uses Redux, I think, but we don’t need to think about that. Today, we’re using it plain.</p><p>Our main App component is a StackNavigator. That means it’s build purely out of screens that stack.</p><pre>// src/index.js<br><br>import {<br>    StackNavigator<br>} from &#39;react-navigation&#39;;<br><br>import { ClimatesScreen, AreasScreen, AccomodationsScreen } from &#39;./Screens&#39;;<br>import PackingScreen from &#39;./PackingScreen&#39;;<br><br>const App = StackNavigator({<br>    Climates: { screen: ClimatesScreen },<br>    Areas: {<br>        screen: AreasScreen,<br>        path: &#39;areas/:climate&#39;<br>    },<br>    Accomodations: {<br>        screen: AccomodationsScreen,<br>        path: &#39;accomodations/:climate/:area&#39;<br>    },<br>    PackingList: {<br>        screen: PackingScreen,<br>        path: &#39;packing/:climate/:area/:accomodation&#39;<br>    }<br>});<br><br>export default App</pre><p>We initiate a new StackNavigator and define 4 screens. Each is a React component that implicitly receives a navigation prop from react-navigation. They’re also going to have to define some options for navigation to use. I’ll show you those in a bit.</p><p>Alongside screens I also defined some paths. We aren’t using them, but react navigation docs say you need them for <a href="https://reactnavigation.org/docs/guides/linking">deep linking</a>. Seems prudent to always add a path.</p><h3>Define the screens</h3><p>Each of our screens needs to define some navigationOptions and a way to navigate somewhere else. Our first 3 screens look almost the same. Sure they load different options for you to click, but they’re all just a list of random pictures with some words.</p><p>They’re implemented like this:</p><pre>// src/Screens.js<br><br>import ListScreen from &#39;./ListScreen&#39;;<br><br>export class ClimatesScreen extends Component {<br>    static navigationOptions = {<br>        title: &quot;Going somewhere?&quot;<br>    }<br><br>    static Climates = [&quot;Tropical&quot;, &quot;Arid&quot;, &quot;Temperate&quot;, &quot;Continental&quot;, &quot;Arctic&quot;]<br><br>    navigate = (climate) =&gt; {<br>        const { navigate } = this.props.navigation;<br><br>        navigate(&#39;Areas&#39;, { climate });<br>    }<br><br>    render() {<br>        const { Climates } = this.constructor;<br><br>        return (<br>            &lt;ListScreen choices={Climates} navigate={this.navigate}<br>                        flickrSearch={(name) =&gt; `${name} landscape`} /&gt;<br>        );<br>    }<br>}</pre><p>The static navigationOptions property defines options for React Navigation. Available options differ depending on which navigator you’re using. In our case we’re setting a title.</p><p>Our 3 list screens also have a list of options, named differently in each of them for absolutely no reason at all. It made sense at the time, but I could’ve abstracted these three components further.</p><p>Our navigate function is a callback we’re passing to ListScreen. It gets a &quot;What was clicked&quot; parameter and passes it on as a navigation param when calling navigation.navigate.</p><p>Calling navigation.navigate moves us to a different screen as defined in the original StackNavigator setup.</p><p>If you need to get fancy with your options, navigationOptions can be a function. You can use it to set a dynamic title like we do in our AreasScreen.</p><pre>// src/Screens.js<br><br>import ListScreen from &#39;./ListScreen&#39;;<br><br>export class ClimatesScreen extends Component {<br>    static navigationOptions = {<br>        title: &quot;Going somewhere?&quot;<br>    }<br><br>    static Climates = [&quot;Tropical&quot;, &quot;Arid&quot;, &quot;Temperate&quot;, &quot;Continental&quot;, &quot;Arctic&quot;]<br><br>    navigate = (climate) =&gt; {<br>        const { navigate } = this.props.navigation;<br><br>        navigate(&#39;Areas&#39;, { climate });<br>    }<br><br>    render() {<br>        const { Climates } = this.constructor;<br><br>        return (<br>            &lt;ListScreen choices={Climates} navigate={this.navigate}<br>                        flickrSearch={(name) =&gt; `${name} landscape`} /&gt;<br>        );<br>    }<br>}</pre><p>A dynamic navigationOptions gets the full navigation object, which let’s us access current navigation params.</p><p>These 3 screens look the same so I suggest <a href="https://github.com/shoutem/school/blob/master/TravelApp/src/Screens.js">checking the source on Github</a> for more details.</p><h3>ListScreen component</h3><p>ListScreen is the component that our main three screens – ClimatesScreen, AreasScreen, AccomodationsScreen – use to render a list of images. Since we don’t need any scrolling or other fancy features, we can build it ourselves without using a proper ListView.</p><p>It’s made out of two components: A ListScreen and a Choice for each entry.</p><pre>class Choice extends Component {<br>    onPress = (event) =&gt; {<br>        this.props.navigate(this.props.name);<br>    }<br><br>    render() {<br>        const { name, flickrSearch } = this.props,<br>              { width } = Dimensions.get(&#39;window&#39;);<br><br>        return (<br>            &lt;TouchableHighlight style={styles.container}<br>                                onPress={this.onPress}&gt;<br>                &lt;View style={styles.container}&gt;<br>                    &lt;FlickrPic name={flickrSearch(name)}<br>                               style={[styles.backgroundImage, { width }]}<br>                               blurRadius={1.2} /&gt;<br>                    &lt;Text style={[styles.bigButtonText, {position: &#39;absolute&#39;}]}&gt;<br>                        {name}<br>                    &lt;/Text&gt;<br>                &lt;/View&gt;<br>            &lt;/TouchableHighlight&gt;<br>        );<br>    }<br>}<br><br>const ListScreen = ({ navigate, choices, flickrSearch }) =&gt; (<br>    &lt;View style={styles.container}&gt;<br>        {choices.map(choice =&gt; &lt;Choice name={choice} key={choice} navigate={navigate} flickrSearch={flickrSearch} /&gt;)}<br>    &lt;/View&gt;<br>)</pre><p>The ListScren component is a View that walks through a list of choices and renders a Choice component for each one. It gets a navigate prop with a callback that navigates to a different screen, and a flickrSearch prop that it uses to build a string to search Flickr with.</p><p>The Choice component itself renders a TouchableHighlight that contains a View with a FlickrPic and some Text.</p><p>When rendered the full list looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*YPCF7N-a5q38YwjZ.png" /></figure><p>The FlickrPic component isn’t very interesting. We already talked about it in depth when building our <a href="https://school.shoutem.com/lectures/build-react-native-music-app-tutorial-part1/">Music App</a>.</p><p>It’s a component that renders an &lt;Image&gt; and looks on Flickr to find it. Search term, flickr fetch, render image.</p><p>You can see it <a href="https://github.com/shoutem/school/blob/master/TravelApp/src/FlickrPic.js">on Github</a>. Starting to think I should release it as an opensource package. Could be useful</p><p>Some logic I added since last time is to try a few different search terms if the first doesn’t come up with a pic. If you’re looking for city+camping and that’s too strict, it tries city camping.</p><p>I have yet to find an unstrict two word search term where Flickr came up empty so further improvements to the logic felt unnecessary.</p><h3>A note on styling</h3><p>We’re doing our own styling in this app. The Shoutem UI Toolkit that we normally use and React Navigation don’t like each other just yet. As far as I know Shoutem is working on it and I’m a terrible opensource community member for not helping</p><p>All our styles fit in a single <a href="https://github.com/shoutem/school/blob/master/TravelApp/src/styles.js">66 line file</a>. I’m not pasting it here because it’s repetitive, but I do want to show you one cool thing I learned.</p><p>Dimensions! The Dimensions API can tell you the size of the screen you’re rendering on! Perfect for full-width images.</p><pre>// src/styles.js<br>  listItem: {<br>      flexDirection: &#39;row&#39;,<br>      justifyContent: &#39;flex-start&#39;,<br>      alignItems: &#39;center&#39;,<br>      width: Dimensions.get(&#39;window&#39;).width,<br>      padding: 10<br>  },</pre><p>Yes, it’s a small thing. A tiny little hack. But you have no idea how much pain I’ve gone through dealing with onLayout callbacks way back in our <a href="https://school.shoutem.com/lectures/build-react-native-mobile-app-tutorial/">React 101</a> and <a href="https://school.shoutem.com/lectures/build-simple-imgur-client-react-native-mobx-tutorial/">Imgur</a> apps.</p><h3>The PackingScreen component</h3><p>We’ve arrived at the workhorse of our travel app. Everything so far has been about getting to this screen where our users Do The Thing that helps their pain.</p><p>Keep forgetting a toothbrush? Now you won’t. Don’t know what to pack for a hike in the tropics? Now you know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*abfZxDz09if4F-mM.png" /></figure><p>The core PackingScreen is a React Navigation TabNavigator. Like this:</p><pre>// src/PackingScreen.js<br><br>const tabBarIcon = (icon) =&gt; ({ tintColor }) =&gt; (<br>    &lt;Image source={icon}<br>           style={[{width: 26, height: 26}, {tintColor: tintColor}]} /&gt;<br>);<br><br>const PackingScreen = TabNavigator({<br>    Toiletries: {<br>        screen: PackingList,<br>        navigationOptions: {<br>            tabBarLabel: &#39;Toiletries&#39;,<br>            tabBarIcon: tabBarIcon(require(&#39;./images/toothbrush.png&#39;))<br>        }<br>    },<br>    Clothes: {<br>        screen: PackingList,<br>        navigationOptions: {<br>            tabBarLabel: &#39;Clothes&#39;,<br>            tabBarIcon: tabBarIcon(require(&#39;./images/shirt.png&#39;))<br>        }<br>    },<br>    Gear: {<br>        screen: PackingList,<br>        navigationOptions: {<br>            tabBarLabel: &#39;Gear&#39;,<br>            tabBarIcon: tabBarIcon(require(&#39;./images/headphones.png&#39;))<br>        }<br>    }<br>}, {<br>    tabBarOptions: {<br>        activeTintColor: &#39;#e91e63&#39;<br>    }<br>});</pre><p>Each of the 3 tabs — Toiletries, Clothes and Gear – renders a PackingList screen, and has some navigationOptions that define a label and an icon. Yes this is a third way to define those, straight in the navigator definition.</p><p>We use an &lt;Image&gt; component to render our icons. They look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*uPj5rDm_hADDjcWr.png" /></figure><h3>PackingList</h3><p>Our PackingList component is built with a FlatList. According to <a href="https://facebook.github.io/react-native/docs/flatlist.html">React Native Docs</a> a FlatList is the best and most efficient way to render a list of things.</p><p>It’s a lot of code so we’ll go step by step.</p><p>We start with the innermost component. A ListItem. We use it to render each entry in our list.</p><pre>// src/PackingList.js<br><br>class ListItem extends PureComponent {<br>    _toggle = () =&gt; {<br>        this.props.onItemToggle(this.props.id)<br>    }<br><br>    _remove = () =&gt; {<br>        this.props.onRemoveItem(this.props.id);<br>    }<br><br>    render() {<br>        const { value, name } = this.props;<br><br>        return (<br>            &lt;View style={styles.listItem}&gt;<br>                &lt;Switch value={value}<br>                        onValueChange={this._toggle} /&gt;<br>                &lt;Text style={styles.listItemText}&gt;{name}&lt;/Text&gt;<br>                &lt;View style={{flex: 1, justifyContent: &#39;flex-end&#39;}}&gt;<br>                    &lt;Button title=&quot;Remove&quot;<br>                            onPress={this._remove}<br>                            style={{textAlign: &#39;right&#39;}}/&gt;<br>                &lt;/View&gt;<br>            &lt;/View&gt;<br>        )<br>    }<br>}</pre><p>Our ListItem renders as a View that contains a Switch, some Text, and a Button. Switch toggles the value of our item via the onItemToggle callback, the Button uses onRemoveItem to remove it from the list.</p><p>Now, the PackingList component is a bit hairy. 91 lines of code.</p><p>Most of that is due to state and callback handling. This is where using Redux or MobX would’ve made our lives easier.</p><p>Here’s the main <strong>state handling part:</strong></p><pre>// src/PackingList.js<br><br>class PackingList extends PureComponent {<br>    state = {<br>        items: []<br>    }<br><br>    constructor(props) {<br>        super(props);<br><br>        this.getItems();<br>    }<br><br>    getItems = () =&gt; {<br>        const { navigation } = this.props;<br><br>        Store.getItems({ navigation })<br>             .then(items =&gt; {<br>                 this.setState({<br>                     items: items.map(item =&gt; {<br>                         if (typeof item.value === &#39;undefined&#39;) {<br>                             item.value = false;<br>                         }<br>                         return item;<br>                     })<br>                 });<br>             });<br>    }</pre><p>Our state holds a list of items. They’re fetched in the constructor with a getItems call. Potentially this fits better in a componentWillMount or componentDidMount lifecycle hook.</p><p>getItems talks to our Store instance, which is neither Redux nor MobX, but a small abstraction built on top of Firebase and AsyncStorage. I’ll show you later.</p><p>From there it gets a list of items that fit in the current navigation path, initializes their value to false if no value exists, and returns them to be saved in this.state.</p><p><strong>The callbacks part</strong> looks like this. It’s a bit of a mess</p><pre>// src/PackingList.js<br>class PackingList extends PureComponent {<br>    // ..<br>    _clearItems = () =&gt; {<br>        const { navigation } = this.props;<br><br>        Store.clearItems({ navigation })<br>             .then(() =&gt; this.getItems());<br>    }<br><br>    _keyExtractor = (item, index) =&gt; item.id;<br><br>    _onItemToggle = (id) =&gt; {<br>        this.setState((state) =&gt; {<br>            const { navigation } = this.props;<br><br>            const items = state.items.map(<br>                item =&gt; {<br>                    item = Object.assign({}, item);<br>                    if (item.id === id) {<br>                        item.value = !item.value;<br>                    }<br>                    return item;<br>                }<br>            );<br><br>            Store.saveItems({ navigation, items });<br><br>            return { items };<br>        });<br>    }<br><br>    _onRemoveItem = (id) =&gt; {<br>        const { navigation } = this.props;<br><br>        Store.removeItem({ navigation, id })<br>             .then(this.getItems);<br>    }</pre><p>_clearItems calls a Store method that goes through items and sets their value to false.</p><p>_keyExtractor is a FlatList requirement. It tells the list how to identify items.</p><p>_onItemToggle is called when you toggle an item. <em>&quot;What, Swizec, why didn’t this also go in Store?&quot;</em> You’re right, it definitely should. I was following the FlatList documentation and built this before I had a Store. Then it worked and I didn’t want to change it</p><p>It creates a new copy of the items array with a flipped value on one of the items.</p><p>_onRemoveItem is similar to clear items. Calls a Store method that removes a single item, then refreshes the local list with this.getItems.</p><p><strong>The rendering part</strong> is easy in comparison. Looks like this:</p><pre>// src/PackingList.js<br><br>class PackingList extends PureComponent {<br>    // ...<br>    <br>    _renderItem = ({ item }) =&gt; (<br>        &lt;ListItem id={item.id}<br>                  onItemToggle={this._onItemToggle}<br>                  onRemoveItem={this._onRemoveItem}<br>                  navigation={this.props.navigation}<br>                  {...item} /&gt;<br><br>    );<br><br>    render() {<br>        const { navigation } = this.props,<br>              { climate, area, accomodation } = navigation.state.params,<br>              { routeName } = navigation.state;<br><br>        return (<br>            &lt;View style={styles.container}&gt;<br>                &lt;Text style={styles.header}&gt;Packing {routeName.toLowerCase()} for {climate.toLowerCase()} weather {accomodation === &#39;Couch&#39; ? &#39;on&#39; : &#39;in&#39;} a {area.toLowerCase()} {accomodation.toLowerCase()}&lt;/Text&gt;<br>                &lt;FlatList data={this.state.items}<br>                          renderItem={this._renderItem}<br>                          keyExtractor={this._keyExtractor}<br>                          contentContainerStyle={styles.packingList} /&gt;<br>                &lt;AddItem navigation={navigation}<br>                         onAdd={this.getItems} /&gt;<br>                &lt;Button title=&quot;Clear packing list&quot;<br>                        onPress={this._clearItems} /&gt;<br>            &lt;/View&gt;<br>        )<br>    }<br>}</pre><p>We have a _renderItem method that uses ListItem to render a single item. Callbacks and properties are passed in. No biggie.</p><p>The main render method is a View that renders a descriptive Text cobbled together from values in navigation.params. A FlatList with our data and some callbacks, and finally an AddItem component that renders an input field with a button.</p><p>When it adds an item, AddItem calls its onAdd callback and triggers a this.getItems call. The managed input with a button is pretty boring so here’s just a <a href="https://github.com/shoutem/school/blob/master/TravelApp/src/AddItem.js">github source link</a>.</p><p>I explain it in the video though</p><p>The final Button calls our _clearItems callback.</p><h3>Talking to AsyncStorage and Firebase</h3><p>Okay, we’ve built the app! You can see a list of items, toggle their values, and navigate around.</p><p>But your packing choices don’t persist through app restarts and there’s no crowdsourcing yet. We add those with our Store object.</p><p>Mind you this is neither a Redux store nor a MobX store. It’s just called Store because it does the job of a data store.</p><p>It starts with imports, Firebase config, and some default items, and ends with an instance export.</p><pre>// src/store.js<br><br>import { AsyncStorage } from &#39;react-native&#39;;<br>import * as firebase from &#39;firebase&#39;;<br><br>const firebaseConfig = {<br>    // copy this from your Firebase Console<br>}<br>firebase.initializeApp(firebaseConfig);<br><br>const ITEMS = {<br>    Toiletries: [<br>        {id: 0, name: &#39;Toothbrush&#39;},<br>        {id: 1, name: &#39;Toothpaste&#39;},<br>        {id: 2, name: &#39;Facewash&#39;}<br>    ],<br>    Clothes: [<br>        {id: 0, name: &#39;Jacket&#39;},<br>        {id: 1, name: &#39;T-Shirts&#39;},<br>        {id: 2, name: &#39;Underpants&#39;}<br>    ],<br>    Gear: [<br>        {id: 0, name: &#39;Laptop&#39;},<br>        {id: 1, name: &#39;Book&#39;},<br>        {id: 2, name: &#39;Phone Charger&#39;}<br>    ]<br>}<br><br>// Store class<br><br>export default new Store();</pre><p>Feel free to steal <a href="https://github.com/shoutem/school/blob/master/TravelApp/src/store.js">my Firebase config</a> from Github. If you do, everyone who reads this tutorial can share packing recommendations.</p><p>The Store class itself is pretty big. We’ll go section by section.</p><p>First we need <strong>helper methods to calculate keys</strong>. You can think of both AsyncStorage and Firebase as big dictionaries. A key tells us which field to look at.</p><pre>class Store {<br>    makeKey({ navigation }) {<br>        const { climate, area, accomodation } = navigation.state.params,<br>              { routeName } = navigation.state;<br><br>        return `@MySuperItemsStore:${climate}/${area}/${accomodation}/${routeName}`;<br>    }<br><br>    firebaseKey({ navigation }) {<br>        const { climate, area, accomodation } = navigation.state.params,<br>              { routeName } = navigation.state;<br><br>        return `${climate}:${area}:${accomodation}:${routeName}`;<br>    }<br><br>}</pre><p>We take navigation route values out of the navigation object and turn them into a string. Colon separator for Firebase and / for AsyncStorage.</p><p>Colons should work in both cases, but slashes don’t work on Firebase. Well, they do, but it’s harder to use because you have to build a real object hierarchy instead of a flat dict.</p><p>AsyncStorage requires that first @Foo part though. It namespaces keys to our app. If I understood <a href="https://facebook.github.io/react-native/docs/asyncstorage.html">the docs</a> correctly, AsyncStorage is global per device. That means shared across apps.</p><p>Seems insecure so surely I misread</p><p>With key helpers in place, we need <strong>a way to </strong><strong>getItems</strong> and merge them between local state in AsyncStorage and global recommendations in Firebase.</p><pre>class Store {<br>    // ...<br>    <br>    getItems({ navigation }) {<br>        const key = this.makeKey({ navigation });<br><br>        return firebase.auth()<br>                       .signInAnonymously()<br>                       .then(() =&gt; new Promise((resolve, reject) =&gt; {<br>                           firebase.database()<br>                                   .ref(this.firebaseKey({ navigation }))<br>                                   .once(&#39;value&#39;, (snapshot) =&gt; {<br>                                       const val = snapshot.val();<br><br>                                       if (val === null) {<br>                                           resolve([]);<br>                                       }else{<br>                                           resolve(val);<br>                                       }<br>                                   })<br>                       }))<br>                       .then(firebaseItems =&gt;<br>                           AsyncStorage.getItem(key).then(<br>                               value =&gt; new Promise((resolve, reject) =&gt; {<br>                                   let items = ITEMS[navigation.state.routeName];<br><br>                                   if (value !== null) {<br>                                       items = JSON.parse(value);<br>                                   }<br><br>                                   Object.keys(firebaseItems).forEach(id =&gt; {<br>                                       if (!items.find(i =&gt; i.id === id)) {<br>                                           items.push(firebaseItems[id]);<br>                                       }<br>                                   });<br><br>                                   AsyncStorage.setItem(key, JSON.stringify(items))<br>                                               .then(() =&gt; resolve(items));<br>                               })));<br>    }</pre><p>In the first part we fetch items from firebase. Sign in anonymously, .then fetch items from a firebase key. .ref.once is callback based, so we wrap it in a Promise.</p><p>With firebaseItems in hand, we talk to AsyncStorage. This one is promise based, but we need to maintain a reference to firebasItems so it’s easier to wrap our stuff in a new Promise than to chain .then calls.</p><p>I think …</p><p>Anyway, when we have both items from firebase and items from AsyncStorage, we merge the two lists together. To avoid duplicate items, we walk through firebaseItems and only add those whose id doesn’t yet exist in the list.</p><p>The implementation with .find is slow in theory, but works okay for small lists, and is not difficult to optimize later. A dict of ids to lookup hint hint.</p><p>When we have the full list, we save it locally with AsyncStorage.setItem and resolve our overall promise to return items.</p><p>The methods to <strong>remove, clear, and save</strong> items are less involved. They look like this:</p><pre>// src/store.js<br><br>class Store {<br>    // ..<br>    <br>    saveItems({ navigation, items }) {<br>        const key = this.makeKey({ navigation });<br><br>        return AsyncStorage.setItem(key, JSON.stringify(items));<br>    }<br><br>    clearItems({ navigation }) {<br>        const key = this.makeKey({ navigation });<br><br>        return this.getItems({ navigation })<br>                   .then(items =&gt; {<br>                       items = items.map(item =&gt; {<br>                           item.value = false;<br>                           return item;<br>                       });<br><br>                       return this.saveItems({ navigation, items });<br>                   });<br>    }<br><br>    removeItem({ navigation, id }) {<br>        const key = this.makeKey({ navigation });<br><br>        return this.getItems({ navigation })<br>                   .then(items =&gt; {<br>                       items = items.filter(item =&gt; item.id !== id);<br>                       return this.saveItems({ navigation, items });<br>                   });<br>    }<br>}</pre><p>saveItems uses AsyncStorage.setItem to overwrite the current list of items. It trusts the new value is correct and doesn’t check anything.</p><p>clearItems gets items, walks through them, sets their values to false and saves the new list. It might be better to use a different getItems method that doesn’t re-fetch from Firebase. Would be a bit faster.</p><p>removeItem is similar to clearItems in that it reads items from store, changes the list (filters 1 entry out), and saves it back.</p><p>Now, <strong>adding crowdsourced items</strong> is more interesting. We have to insert a new item into both AsyncStorage and Firebase. That looks like this:</p><pre>// src/store.js<br><br>class Store {<br>    // ...<br>    <br>    addItem({ navigation, text }) {<br>        const key = this.makeKey({ navigation });<br><br>        return firebase.auth()<br>                       .signInAnonymously()<br>                       .then(() =&gt; {<br>                           const itemRef = firebase.database()<br>                                                   .ref(this.firebaseKey({ navigation }))<br>                                                   .push();<br><br>                           const item = {<br>                               id: itemRef.key,<br>                               name: text<br>                           };<br><br>                           itemRef.set(item);<br><br>                           return this.getItems({ navigation })<br>                       })<br><br>    }</pre><p>Just like we did when reading from firebase, we start by authenticating anonymously.</p><p>.then we create a new itemRef with a firebase .push(). We use it to create a new item with an id and a name and .set it on Firebase.</p><p>When the item is set, we get a new list of items and return it. Having been pushed to Firebase ensures our item is added to the updated list.</p><h3>Happy crowdsourced traveling</h3><p>Your crowdsourced travel app is complete. You can choose from 5 * 5 * 5 = 125 different packing lists, add recommendations for all to see, and never forget your toothbrush again.</p><p>Wonderful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*SHGOi14ZE7FWr9vj.gif" /></figure><p>You should consider <a href="http://eepurl.com/cxTnOL">subscribing by email</a> to join 1,500+ coders receiving a new app build tutorial every 2 weeks.</p><h3>Exercises left to the reader</h3><p>Left as an exercise to the reader. What a wonderful phrase!</p><p>There’s two of those in this tutorial. Removing items from lists doesn’t work right now. Each item removes from AsyncStorage like it’s supposed to, then promptly repopulates from Firebase.</p><p>Oops.</p><p>Ideally, you could delete items you don’t care to pack. This shouldn’t affect global recommendations stored in Firebase.</p><p>Another bug is that PackingList sometimes renders stale data. I’m not sure why, but when you move around the app without refreshing it sometimes renders the first list you ever saw.</p><p>If you figure it out, please let me know and I’ll add your fix to this tutorial.</p><p>Happy hacking.</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/tutorial-build-crowdsourced-react-native-travel-app-react-navigation-asyncstorage-firebase/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385304f7b431" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/tutorial-build-a-crowdsourced-react-native-travel-app-with-react-navigation-asyncstorage-and-385304f7b431">Tutorial: Build a crowdsourced react native Travel App with react-navigation, AsyncStorage, and…</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native SoundCloud streaming app tutorial — React Native School]]></title>
            <link>https://medium.com/react-native-development/react-native-soundcloud-streaming-app-tutorial-react-native-school-55879db01d30?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/55879db01d30</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Thu, 08 Jun 2017 17:00:23 GMT</pubDate>
            <atom:updated>2017-06-08T14:28:04.917Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FFcf-tgSI3x0%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DFcf-tgSI3x0&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FFcf-tgSI3x0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e31627140064f22dd216d44516c084/href">https://medium.com/media/66e31627140064f22dd216d44516c084/href</a></iframe><p><a href="https://school.shoutem.com/lectures/build-react-native-music-app-tutorial-part1/">Two weeks ago we built a React Native Music App</a> that showed a list of music genres with album art from Flickr. When you picked a type of music to play, we fetched a list of songs from SoundCloud.</p><p>Today we’re adding the ability to stream music from SoundCloud. After trying 3 or 4 different React Native sound libraries, I found one that works with remote file streaming: <a href="https://github.com/react-native-community/react-native-video">react-native-video</a></p><p>This has something to do with which native component libraries use to play sound. Most are built on <a href="https://developer.apple.com/reference/avfoundation/avplayer">AVPlayer</a>, which can play only local files. But react-native-video uses <a href="https://developer.apple.com/reference/avfoundation/avaudioplayer">AVAudioPlayer</a>, which supports network files.</p><p>¯_(ツ)_/¯</p><p>The trick is to use an invisible &lt;Video&gt; component to play music.</p><p><strong>Here’s what we’re building today:</strong></p><ul><li>a Player component with play/pause previous/next controls</li><li>a SoundCloud Waveform visualization</li><li>showing current song in the iOS Control Center</li><li>Redux wiring to make it all work</li></ul><p>If you want to see how I built these additions, you can check out the livecoding archive on <a href="https://www.youtube.com/watch?v=BMvoGWDAEbw">my personal YouTube channel</a>. I forgot to stream the last hour or two of the build, but the rest is there 🙂</p><p>You can see the <a href="https://github.com/shoutem/school/tree/e396d6db4c7b2ccd73553cb886998568302f0528/MusicApp">full code on GitHub</a>.</p><p>As always, you should <a href="http://eepurl.com/cxTnOL">subscribe by email</a> to join 1500+ devs eagerly awaiting a new React Native every 2 weeks.</p><p><strong>But first, a public service announcement!</strong></p><p>In our last tutorial I gave you convoluted instructions on how to downgrade React Native to 0.43.3 after running react-native init. Due to changes in native code, those instructions no longer work.</p><p>Here’s how you init a new React Native app with any version you want:</p><pre>$ react-native init MusicApp --version react-native@0.43.3</pre><p>That little trick would’ve saved me <em>hours</em> of futile reinstallation steps and node_modules cleanups.</p><p>PS: We’re doing this because React Native moves fast and some of the libraries I like to use don’t work with 0.44.x.</p><h3>Redux Reducer for player controls</h3><p>Let’s start with our business logic. I find code easier to understand, if I know its actions and reducers. At least on a subconscious level. I rarely build the actions and reducers first even though I should 🙂</p><p>We already have the logic for loading songs, genres, and Flickr images <a href="https://school.shoutem.com/lectures/build-react-native-music-app-tutorial-part1/">from last time</a>. We have to add the music playing logic.</p><p>A music player needs to know:</p><ul><li>what’s the current song</li><li>whether it’s paused</li></ul><p>And it needs to issue these commands:</p><ul><li>toggle pausedness</li><li>move to next song</li><li>move to previous song</li></ul><p>To achieve this, I split our monolithic reducer into 3 parts.</p><pre>// src/reducer.js<br><br>const rootReducer = combineReducers({<br>    currentlyPlaying,<br>    songs,<br>    genres<br>});</pre><p>currentlyPlaying handles the current song and its pausedness. songs holds a list of songs for each genre, and genres is an array of objects that never changes.</p><p>We explained how the songs and genres reducers work last time. Here’s how they look after my reorganization:</p><pre>// src/reducer.js<br>onst initialGenres = [&quot;Alternative Rock&quot;, &quot;Ambient&quot;, &quot;Classical&quot;, &quot;Country&quot;, &quot;EDM&quot;,<br>                       &quot;Dancehall&quot;, &quot;Deep House&quot;, &quot;Disco&quot;, &quot;Drum &amp; Bass&quot;, &quot;Dubstep&quot;, &quot;Electronic&quot;,<br>                       &quot;Folk&quot;, &quot;Singer-Songwriter&quot;, &quot;Rap&quot;, &quot;House&quot;, &quot;Indie&quot;, &quot;Jazz &amp; Blues&quot;,<br>                       &quot;Latin&quot;, &quot;Metal&quot;, &quot;Piano&quot;, &quot;Pop&quot;, &quot;R&amp;B &amp; Soul&quot;, &quot;Reggae&quot;, &quot;Reggaeton&quot;,<br>                       &quot;Rock&quot;, &quot;Soundtrack&quot;, &quot;Techno&quot;, &quot;Trance&quot;, &quot;Trap&quot;, &quot;Triphop&quot;].map(<br>                           (name, i) =&gt; ({<br>                               id: i,<br>                               name<br>                           }));<br>                           <br>const songs = (state = {}, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;FOUND_SONGS&#39;:<br>            const { songs, genre } = action;<br>            return Object.assign({}, state.songs,<br>                                 {<br>                                     [genre.id]: songs<br>                                 })<br>        default:<br>            return state;<br>    }<br>};<br><br>const genres = (state = initialGenres, action) =&gt; {<br>    switch (action.type) {<br>        default:<br>            return state;<br>    }<br>}</pre><p>The new currentlyPlaying reducer is more fun. It tells us what our music app is doing right now.</p><pre>// src/reducer.js<br><br>const initialCurrentlyPlaying = {<br>    genre: {},<br>    songIndex: -1,<br>    paused: false<br>}<br><br>const currentlyPlaying = (state = initialCurrentlyPlaying, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;PLAYING_GENRE&#39;:<br>            return Object.assign({}, state,<br>                                 {<br>                                     genre: action.genre,<br>                                     paused: false,<br>                                     currentTime: 0<br>                                 });<br>        case &#39;SET_CURRENT_SONG&#39;:<br>            return Object.assign({}, state,<br>                                 {<br>                                     songIndex: action.index<br>                                 });<br>        case &#39;UPDATE_PAUSED&#39;:<br>            return Object.assign({}, state,<br>                                 {<br>                                     paused: action.paused<br>                                 });<br>        case &#39;SET_PLAY_TIME&#39;:<br>            return Object.assign({}, state,<br>                                 {<br>                                     currentTime: action.currentTime<br>                                 });<br><br>        default:<br>            return state;<br>    }<br>}</pre><p>Initially, we know there’s no current genre, no current songIndex and we’re not paused. currentTime is implicitly null as well.</p><p>When you choose a new genre to play, we set the genre, set paused to false and reset currentTime. songIndex changes when SET_SONG_INDEX happens. There’s also a transformation to set pausedness and one to update the current time.</p><p>Using the songIndex approach instead of shoving the current song in there makes previous/next actions easier. Change the index -1 or +1 and it works.</p><p>This approach does make getting the current song from state a little harder, but that’s okay. You’ll see it’s not so bad.</p><h3>Redux Actions for player controls</h3><p>Our actions follow the outline we set in the reducer, except there’s more of them. We need some extra thunk actions so we can talk to the iOS Control Center and tell it what’s going on.</p><pre>// src/actions.js<br><br>// playGenre is updated from last time<br>export const playGenre = (genre) =&gt; {<br>    return function (dispatch) {<br>        dispatch(playingGenre(genre));<br><br>        search(genre.name)<br>          .then(result =&gt; {<br>              dispatch(foundSongs(result.collection, genre));<br>              dispatch(setCurrentSong(0));<br>              dispatch(playCurrentSong());<br>          });<br>    }<br>};<br><br>export const setCurrentSong = (index) =&gt; ({<br>    type: &#39;SET_CURRENT_SONG&#39;,<br>    index<br>});<br><br>export const playCurrentSong = () =&gt; {<br>    return function (dispatch, getState) {<br>        const { songs, currentlyPlaying } = getState();<br><br>        let song = null;<br><br>        if (currentlyPlaying.genre &amp;&amp; currentlyPlaying.songIndex &gt;= 0) {<br>            if (songs[currentlyPlaying.genre.id]) {<br>                song = songs[currentlyPlaying.genre.id][currentlyPlaying.songIndex];<br>            }<br>        }<br><br>        MusicControl.enableControl(&#39;seekForward&#39;, false);<br>        MusicControl.enableControl(&#39;seekBackward&#39;, false);<br>        MusicControl.enableControl(&#39;skipForward&#39;, false);<br>        MusicControl.enableControl(&#39;skipBackward&#39;, false);<br>        MusicControl.enableBackgroundMode(true);<br><br>        MusicControl.on(&#39;play&#39;, () =&gt; dispatch(playCurrentSong()));<br>        MusicControl.on(&#39;pause&#39;, () =&gt; dispatch(pauseCurrentSong()));<br>        MusicControl.on(&#39;nextTrack&#39;, () =&gt; dispatch(playNextSong()));<br>        MusicControl.on(&#39;previousTrack&#39;, () =&gt; dispatch(playPreviousSong()));<br><br>        if (song) {<br>            MusicControl.setNowPlaying({<br>                title: song.title || &quot;&quot;,<br>                artwork: song.artwork_url || &quot;&quot;,<br>                artist: song.user.username || &quot;&quot;,<br>                genre: song.genre || &quot;&quot;,<br>                duration: song.duration/1000,<br>                description: song.description || &quot;&quot;,<br>                color: 0xFFFFFFF,<br>                date: song.created_at,<br>                rating: true<br>            });<br><br>            MusicControl.updatePlayback({<br>                state: MusicControl.STATE_PLAYING<br>            });<br>        }<br><br>        dispatch(_updatePaused(false));<br>    }<br>};<br><br>export const pauseCurrentSong = () =&gt; {<br>    return function (dispatch) {<br>        MusicControl.updatePlayback({<br>            state: MusicControl.STATE_PAUSED<br>        });<br><br>        dispatch(_updatePaused(true));<br>    }<br>};<br><br>const _updatePaused = (paused) =&gt; ({<br>    type: &#39;UPDATE_PAUSED&#39;,<br>    paused<br>});<br><br>export const playNextSong = () =&gt; {<br>    return function (dispatch, getState) {<br>        const { songIndex, genre } = getState().currentlyPlaying,<br>              songs = getState().songs[genre.id];<br><br>        dispatch(setCurrentSong((songIndex+1)%songs.length));<br>        dispatch(playCurrentSong());<br>    }<br>};<br><br>export const playPreviousSong = () =&gt; {<br>    return function (dispatch, getState) {<br>        const { songIndex } = getState().currentlyPlaying,<br>              newIndex = songIndex - 1;<br><br>        dispatch(setCurrentSong(newIndex &lt; 0 ? 0 : newIndex));<br>        dispatch(playCurrentSong());<br>    }<br>}<br><br>export const updatePlayTime = (currentTime) =&gt; {<br>    return function (dispatch) {<br>        MusicControl.updatePlayback({<br>            state: MusicControl.STATE_PLAYING,<br>            elapsedTime: currentTime<br>        });<br><br>        dispatch(_setPlayTime(currentTime));<br>    }<br>}<br><br>const _setPlayTime = (currentTime) =&gt; ({<br>    type: &#39;SET_PLAY_TIME&#39;,<br>    currentTime<br>});</pre><p>The basic idea behind these is that we have API actions and setter actions. API actions expose an interface for our components to use.</p><p>They can setCurrentSong, playCurrentSong, playNextSong, playPreviousSong and updatePlayTime. These update MusicControl and call their corresponding setter action.</p><p>We have fewer setter than API actions because there’s overlap. Both playNext andplayPrevious can use the same setCurrentSong action for instance.</p><p>We also updated playGenre to set and play the current song after fetching a list of ten songs from SoundCloud.</p><p>There’s a lot going on in the playCurrentSong action. Let me explain.</p><h3>MusicControl talks to iOS Control Center / Android Notification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*ksspgOXitR89ZddV.png" /></figure><p>We’re using Tanguy Antoine’s <a href="https://github.com/tanguyantoine/react-native-music-control">react-native-music-control</a> to talk to our device’s native music controls. I like the library because it has a simple API.</p><p>In fact, you just saw all of its API. It’s all in the actions 🙂</p><p>Let’s look at playCurrentSong again.</p><pre>// src/actions.js<br><br>export const playCurrentSong = () =&gt; {<br>    return function (dispatch, getState) {<br>        const { songs, currentlyPlaying } = getState();<br><br>        // get current song<br>        let song = null;<br><br>        if (currentlyPlaying.genre &amp;&amp; currentlyPlaying.songIndex &gt;= 0) {<br>            if (songs[currentlyPlaying.genre.id]) {<br>                song = songs[currentlyPlaying.genre.id][currentlyPlaying.songIndex];<br>            }<br>        }<br>        <br>        // set up OS music controls<br>        MusicControl.enableControl(&#39;seekForward&#39;, false);<br>        MusicControl.enableControl(&#39;seekBackward&#39;, false);<br>        MusicControl.enableControl(&#39;skipForward&#39;, false);<br>        MusicControl.enableControl(&#39;skipBackward&#39;, false);<br>        MusicControl.enableBackgroundMode(true);<br><br>        // listen to control callbacks<br>        MusicControl.on(&#39;play&#39;, () =&gt; dispatch(playCurrentSong()));<br>        MusicControl.on(&#39;pause&#39;, () =&gt; dispatch(pauseCurrentSong()));<br>        MusicControl.on(&#39;nextTrack&#39;, () =&gt; dispatch(playNextSong()));<br>        MusicControl.on(&#39;previousTrack&#39;, () =&gt; dispatch(playPreviousSong()));<br><br>        // update what&#39;s playing<br>        if (song) {<br>            MusicControl.setNowPlaying({<br>                title: song.title || &quot;&quot;,<br>                artwork: song.artwork_url || &quot;&quot;,<br>                artist: song.user.username || &quot;&quot;,<br>                genre: song.genre || &quot;&quot;,<br>                duration: song.duration/1000,<br>                description: song.description || &quot;&quot;,<br>                color: 0xFFFFFFF,<br>                date: song.created_at,<br>                rating: true<br>            });<br><br>            MusicControl.updatePlayback({<br>                state: MusicControl.STATE_PLAYING<br>            });<br>        }<br><br>        dispatch(_updatePaused(false));<br>    }<br>};</pre><p>In the first part, we get the current song. This is what I meant earlier when I said it’s trickier than strictly necessary. It’s also what in a MobX app would’ve been an <a href="https://mobx.js.org/refguide/computed-decorator.html">@computed</a> value, but Redux doesn’t have that concept I think.</p><p>Then we disable a few MusicControl options that don’t make sense with our app. Seeking through songs is useful in theory, but I didn’t want to deal with potential complications around streaming.</p><p>After that, we subscribe to different events. In theory, users can use the Control Center to play/pause our music, but it doesn’t work in my simulator. I was not able to figure out why, but the callbacks never even fire.</p><p>I’ll submit a bug, yes. This article doubles as my <em>show us what happens and in what situation</em> 🙂</p><p>In the end, we tell MusicControl which song we’re playing. This part works well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*Xwe5AzLdS05WfDSJ.png" /></figure><h3>The Player component</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*zVvDonObwXJDzJPD.gif" /></figure><p>With our Redux reducer and actions wired up, it’s time to build the Player component. This is the component that showed a SoundCloud URL and was called Playing in <a href="https://school.shoutem.com/lectures/build-react-native-music-app-tutorial-part1/">React Native Music App part 1</a>.</p><p>You can almost think of Player as a mini app inside our big app. 4 components make up our player:</p><ul><li>Player holds everything together, talks to react-native-video</li><li>Controls renders the play/pause prev/next buttons</li><li>Timer shows playing time</li><li>SoundCloudWave renders a SoundCloud waveform</li></ul><p>Maybe I should [properly] opensource that last one</p><p>Let’s walk through them one by one. Top to bottom.</p><h3>Player component</h3><p>The Player component holds everything together. It’s a full component because we need event callbacks and some helpful getters.</p><pre>// src/Player.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { Text, Spinner, Card, Subtitle, Icon, View } from &#39;@shoutem/ui&#39;;<br>import Video from &#39;react-native-video&#39;;<br><br>import { updatePlayTime, playNextSong } from &#39;./actions&#39;;<br>import { streamUrl } from &#39;./soundcloudHelper&#39;;<br>import SoundCloudWave from &#39;./SoundCloudWave&#39;;<br>import Controls from &#39;./Controls&#39;;<br>import Timer from &#39;./Timer&#39;;<br><br>class Player extends Component {<br>    get song() {<br>        const { songs, currentlyPlaying } = this.props;<br><br>        let song = null;<br><br>        if (currentlyPlaying.genre &amp;&amp; currentlyPlaying.songIndex &gt;= 0) {<br>            if (songs[currentlyPlaying.genre.id]) {<br>                song = songs[currentlyPlaying.genre.id][currentlyPlaying.songIndex];<br>            }<br>        }<br><br>        return song;<br>    }<br><br>    get percentPlayed() {<br>        const { currentlyPlaying: { currentTime } } = this.props;<br><br>        return currentTime / (this.song.full_duration/1000);<br>    }<br><br>    onPlayProgress = ({ currentTime }) =&gt; {<br>        this.props.dispatch(updatePlayTime(currentTime))<br>    }<br><br>    onPlayEnd = () =&gt; {<br>        this.props.dispatch(playNextSong())<br>    }<br><br>    render() {<br>        // ...<br>        }<br>}<br><br>export default connect(<br>    (state) =&gt; ({<br>        currentlyPlaying: state.currentlyPlaying,<br>        songs: state.songs<br>    })<br>)(Player);</pre><p>Right, that looks like a lot of code, but you’ll recognize a lot of it.</p><p>We start with a bunch of imports and declare a new Player component. We connect it to our Redux store when exporting and feed it our currentlyPlaying and songs data as props.</p><p>Inside the component we have a get song getter. Same as the code we had earlier in our playCurrentSong action. Gets the current song object.</p><p>percentPlayed takes currentTime and the song’s full_duration and tells us how far we’ve gotten. We’ll use this to fill the waveform.</p><p>onPlayProgress and onPlayEnd are &lt;Video&gt; callbacks. The first fires every 250ms and tells us how far into the song we are. The latter fires when the song is over. We use it to progress through the playlist.</p><p>Our render method looks like this:</p><pre>// src/Player.js<br><br>class Player extends Component {<br>    // ...<br><br>    render() {<br>        const { currentlyPlaying: { paused, currentTime } } = this.props,<br>              { dispatch } = this.props;<br><br>        if (!this.song) {<br>            return (<br>                &lt;Card style={{height: 85, alignItems: &quot;center&quot;}}&gt;<br>                    &lt;Spinner /&gt;<br>                &lt;/Card&gt;<br>            );<br>        }<br><br>        return (<br>            &lt;Card style={{height: 85, alignItems: &#39;center&#39;}}&gt;<br>                &lt;Video source={{uri: streamUrl(this.song.uri) }}<br>                       ref=&quot;audio&quot;<br>                       volume={1.0}<br>                       muted={false}<br>                       paused={paused}<br>                       playInBackground={true}<br>                       playWhenInactive={true}<br>                       onProgress={this.onPlayProgress}<br>                       onEnd={this.onPlayEnd}<br>                       resizeMode=&quot;cover&quot;<br>                       repeat={false}/&gt;<br><br>                &lt;View style={{position: &#39;absolute&#39;, top: 0, height: 85}}&gt;<br>                    &lt;SoundCloudWave song={this.song} width={180} height={85}<br>                                    percent={this.percentPlayed}/&gt;<br>                &lt;/View&gt;<br><br>                &lt;View style={{position: &#39;absolute&#39;, top: 0, height: 85, alignItems: &#39;center&#39;}}&gt;<br>                    &lt;Controls /&gt;<br>                    &lt;Timer currentTime={currentTime} /&gt;<br>                &lt;/View&gt;<br>            &lt;/Card&gt;<br>        );<br>    }<br>}</pre><p>We render a &lt;Spinner&gt; component, if the current song is still loading. Yes, we could have an extra boolean on the Redux store that told us when we’re done loading, but meh. This is easier</p><p>Once we have the song, we render an invisible &lt;Video&gt; component, give it our streamUrl, tell it whether music is paused, ask it to playInBackground and playWhenInactive, and wire up our callbacks. playInBackground and playWhenInactive are important because they let us play music even you close the app.</p><p>Our &lt;Video&gt; is implicitly invisible because it doesn’t have size styles.</p><p>Underneath the &lt;Video&gt;, we render two overlapping &lt;View&gt; components. That’s what the inline style definitions are for. Kinda messy, but I don’t think the styles are general enough to warrant a proper StyleSheet definition.</p><p>The first &lt;View&gt; holds a &lt;SoundCloudWave&gt; component and the overlay holds our &lt;Controls&gt; and our &lt;Timer&gt;.</p><h3>Controls and Timer</h3><p>The Controls and Timer components are simple functional stateless components. Redux makes Controls easy because all the logic went into actions and reducers, and Timer just displays the currentTime.</p><pre>// src/Controls.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { View, Icon } from &#39;@shoutem/ui&#39;;<br><br>import {<br>    playCurrentSong,<br>    pauseCurrentSong,<br>    playNextSong,<br>    playPreviousSong<br>} from &#39;./actions&#39;;<br><br>export default connect(<br>    (state) =&gt; ({<br>        paused: state.currentlyPlaying.paused<br>    })<br>)(({ paused, dispatch }) =&gt; (<br>    &lt;View styleName=&quot;horizontal space-between&quot; style={{paddingTop: 30}}&gt;<br>        &lt;Icon name=&quot;left-arrow&quot; onPress={() =&gt; dispatch(playPreviousSong())} /&gt;<br><br>        {paused<br>         ? &lt;Icon name=&quot;play&quot; onPress={() =&gt; dispatch(playCurrentSong())}/&gt;<br>         : &lt;Icon name=&quot;pause&quot; onPress={() =&gt; dispatch(pauseCurrentSong())} /&gt;<br>         }<br><br>        &lt;Icon name=&quot;right-arrow&quot; onPress={() =&gt; dispatch(playNextSong())} /&gt;<br>    &lt;/View&gt;<br>));</pre><p>Import actions, create a connect-ed component, return a &lt;View&gt; that renders 3 icons. One for previous, one for play/pause and one for next.</p><p>onPress callbacks are wired directly into dispatching Redux actions.</p><pre>// src/Timer.js<br><br>import React from &#39;react&#39;;<br>import { View, Text } from &#39;@shoutem/ui&#39;;<br><br>const Timer = ({ currentTime }) =&gt; (<br>    &lt;View styleName=&quot;horizontal h-end&quot;&gt;<br>        &lt;Text&gt;{Math.floor(currentTime/60)} : {Math.floor(currentTime%60)}&lt;/Text&gt;<br>    &lt;/View&gt;<br>);<br><br>export default Timer;</pre><p>Timer renders a View with some Text. We take the currentTime in seconds and convert it into minutes : seconds.</p><p>I’m not even sure Timer warranted its own component, but it does make Player‘s render method easier to read. ¯_(ツ)_/¯</p><h3>SoundCloudWave</h3><p>I found SoundCloudWave the most funnest component in this project to work on. It’s a cheap knockoff of SoundCloud’s famous waveforms.</p><p>We visualize the shape of a song as a series of grey bars. As the song progresses, we color those bars orange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*RCMD1ZACErD9PJIE.gif" /></figure><p>Here’s how that looks in code:</p><pre>// src/SoundCloudWave.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { View } from &#39;@shoutem/ui&#39;;<br>import _ from &#39;lodash&#39;;<br><br>import { scaleLinear } from &#39;d3-scale&#39;;<br>import { mean } from &#39;d3-array&#39;;<br><br>const ACTIVE = &#39;rgba(255, 85, 0, 0.6)&#39;,<br>      INACTIVE = &#39;rgba(85, 85, 85, 0.3)&#39;;<br><br>class SoundCloudWave extends Component {<br>    state = {<br>        waveform: null<br>    }<br><br>    componentDidMount () {<br>        this.fetchWaveForm();<br>    }<br><br>    componentWillReceiveProps(nextProps) {<br>        if (this.state.waveform_url !== nextProps.song.waveform_url) {<br>            this.fetchWaveForm();<br>        }<br>    }<br><br>    fetchWaveForm() {<br>        const { waveform_url } = this.props.song;<br><br>        fetch(waveform_url)<br>          .then(res =&gt; res.json())<br>          .then(json =&gt; this.setState({<br>              waveform: json,<br>              waveform_url: waveform_url<br>          }));<br>    }<br><br>    color(bars, bar_n) {<br>        return bar_n/bars.length &lt; this.props.percent ? ACTIVE : INACTIVE;<br>    }<br><br>    render() {<br>        // ...<br>    }<br>}<br><br>export default SoundCloudWave;</pre><p>You can think of the component as split into two parts. There’s some logic to fetch waveform JSON data and save it in local state, and there’s some rendering logic.</p><p>We’re using local state because much like the album art component, nobody outside SoundCloudWave cares about that info.</p><p>Fetching happens in fetchWaveForm. We’re using an ES6 fetch() and storing the data raw in local state. The function is called every time our component mounts, or the waveform_url info changes. This indicates a new song.</p><pre>// src/SoundCloudWave.js<br><br>class SoundCloudWave extends Component {<br>    // ..<br>    <br>    render() {<br>        if (!this.state.waveform) return null;<br><br>        const { waveform } = this.state,<br>              { percent } = this.props;<br><br>        let chunks = _.chunk(waveform.samples, waveform.width/(this.props.width/3)),<br>            height = scaleLinear().domain([0, waveform.height])<br>                                  .range([0, this.props.height]);<br><br>        return (<br>            &lt;View styleName=&quot;horizontal&quot; style={{width: this.props.width, height: this.props.height}}&gt;<br>                {chunks.map((chunk, i) =&gt; (<br>                    &lt;View style={{backgroundColor: this.color(chunks, i),<br>                                  width: 2,<br>                                  marginRight: 1,<br>                                  height: height(mean(chunk))}}<br>                    key={i}/&gt;<br>                 ))}<br>            &lt;/View&gt;);<br>    }<br>}</pre><p>The render method probably looks confusing if you’re not used declarative data visualization. Here’s how it works</p><p>We take our data, the waveform.samples, which is a series of numbers. Each number tells us how tall that sample should be based on some metric SoundCloud came up with. I think it has to do with song intensity.</p><p>We chunk that list into as many bars as we have room for. Each is 2px wide with a 1px margin, so in a 180px widget, we have room for 60 bars.</p><p>Each will be as hight as the average or mean() of values in that chunk of data.</p><p>We’re using a D3 scaleLinear to help us translate between SoundCloud dimensions and our dimensions. You can think of it as a linear function. If waveform.height is 150 and our prop.height is 85, then height(150) returns 85. height(75) returns 42 and so on.</p><p>The render itself is a bunch of &lt;View&gt; components. The outer view creates space with a width and a height and packs all children horizontally. Inner views represent one bar each. Orange before the play percentage threshold, gray after.</p><p>I don’t know if using a bunch of views is <em>the best</em> way to render a bar chart in React Native … it’s akin to using divs on the web. You’d opt for SVG in a browser.</p><p>I’m sure React Native can render SVGs, but I wanted to Just Get It Working 🙂</p><h3>Fin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*YWmT8WtBmfjTMwymk_qyZw.gif" /></figure><p>Your MusicApp is complete. It shows a genre selector with random album art from Flickr, it lets you play music, it shows beautiful SoundCloud waveforms when you press play.</p><p>What more do you want?</p><p>Native music controls to work if you know how to fix that, <a href="https://github.com/shoutem/school/tree/e396d6db4c7b2ccd73553cb886998568302f0528/MusicApp">PRs and comments</a> are welcome.</p><p><a href="http://eepurl.com/cxTnOL">Join 1500+ devs</a> eagerly awaiting a new React Native every 2 weeks.</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/react-native-soundcloud-streaming-app-tutorial-part-2/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55879db01d30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/react-native-soundcloud-streaming-app-tutorial-react-native-school-55879db01d30">React Native SoundCloud streaming app tutorial — React Native School</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New awesome tutorial of building Music Player APP with React Native]]></title>
            <link>https://medium.com/react-native-development/new-awesome-tutorial-of-building-music-player-app-with-react-native-f5f139d2e2fd?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f5f139d2e2fd</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Andrey Nikishaev]]></dc:creator>
            <pubDate>Tue, 06 Jun 2017 09:34:18 GMT</pubDate>
            <atom:updated>2017-06-06T09:34:18.017Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/react-native-development/build-a-react-native-music-app-tutorial-part-1-react-native-school-292b31b7d002">Read the article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5f139d2e2fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/new-awesome-tutorial-of-building-music-player-app-with-react-native-f5f139d2e2fd">New awesome tutorial of building Music Player APP with React Native</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a React Native Music App tutorial, part 1 — React Native School]]></title>
            <link>https://medium.com/react-native-development/build-a-react-native-music-app-tutorial-part-1-react-native-school-292b31b7d002?source=rss----294c69a8d75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/292b31b7d002</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Tue, 06 Jun 2017 09:32:59 GMT</pubDate>
            <atom:updated>2017-06-06T09:13:47.881Z</atom:updated>
            <content:encoded><![CDATA[<p>Nikolai asked <em>“I’m curious how to make a basic audio player in React Native? A way to play from a remote location”</em>, so here we are: Build a React Native Music App tutorial!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FuqnFEcrbnsA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DuqnFEcrbnsA&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FuqnFEcrbnsA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfda5325bbb9950bdb433905fbc90f0e/href">https://medium.com/media/cfda5325bbb9950bdb433905fbc90f0e/href</a></iframe><p>Our app loads as a list of music genres. We find the “album” art on Flickr, load a list of songs from SoundCloud, and stream music from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*0XO8zoLOIHzSSblI.gif" /></figure><p>Well, we’re <em>going to</em> stream from SoundCloud. Right now we show a direct link to the stream.</p><p>We’re building our Music App in two parts because React Native moves fast and breaks things. I ran into build issues with the <a href="https://github.com/tlenclos/react-native-audio-streaming">react-native-audio-streaming</a> library and haven’t figured them out yet.</p><p>On the other hand SoundCloud is slow to issue API keys as well. Manual process, takes up to a month … but I found a way around that.</p><p>But something not compiling, that’s what broke us. Next time it’ll work!</p><p><a href="http://eepurl.com/cxTnOL">Subscribe by email</a> and make sure you don’t miss React Native Music App Part 2.</p><p><strong>Here’s what you will learn today:</strong></p><ul><li>how to use the Shoutem UI Toolkit GridView</li><li>using Redux for state management</li><li>hacking Flickr and SoundCloud APIs</li><li>how to painlessly downgrade React Native, if necessary</li></ul><p>If you want to see how I built this from scratch, you can check out the livecoding archive on <a href="https://www.youtube.com/watch?v=BMvoGWDAEbw">my personal YouTube channel</a>.</p><p>You can see the <a href="https://github.com/shoutem/school/tree/48b6afa4bdf6894375cdba698f13dc32a3094e7c/MusicApp">full code on GitHub</a>.</p><h3>Setup project</h3><p>As of this writing, May 2017, creating a new React Native project gives you react-native 0.44.0 and React 16 alpha. That’s okay, new tech is great. I think having alpha version libraries by default is an odd choice, but I’m sure the maintainers know what they’re doing.</p><p>React Native’s fast pace puts us in a pickle, however. Because of some breaking changes, the Shoutem UI Toolkit we’ve (read: I’ve) gotten used to for styling doesn’t support react-native 0.44.x yet. I’m sure it will soon, but right now we have to init our app, then downgrade.</p><p>But we can keep React 16. Yay 🙂</p><p><em>Update May 30, 2017: A better way to “downgrade” React Native is to init with the correct version in the first place. Like this:</em></p><pre>$ react-native init MusicApp --version react-native@0.43.3</pre><p>Init the app:</p><pre>$ react-native init MusicApp<br>$ cd MusicApp</pre><p>Then open MusicApp/package.json and change this line:</p><pre>// package.json<br>&quot;react-native&quot;: &quot;0.44.0&quot;, ---&gt; &quot;react-native&quot;: &quot;0.43.0&quot;</pre><p>React Native version goes from 0.44.0 to 0.43.0.</p><p>Now you’re ready to install dependencies for our music app. Like this:</p><pre>$ rm -rf node_modules/react-native<br>$ npm install react-native @shoutem/ui react-redux redux redux-logger redux-thunk<br>$ react-native link<br>$ mkdir src</pre><p>If you run $ react-native run-ios, you should see a working default React Native app. The one that tells you that everything is okay and your setup worked.</p><p>Note, we’re not installing react-native-audio-streaming just yet. It requires special steps that I haven’t quite figured out. We’ll install it in Part 2. Don’t forget to <a href="http://eepurl.com/cxTnOL">subscribe so you don’t miss it</a>.</p><p>We’ll put all our code in the src/ directory, so you should change index.&lt;yourplatform&gt;.js to import App from src/ and render &lt;App /&gt;. This makes it easier to share our code across both iOS and Android.</p><h3>Listing genres with Flickr images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WB8o2UlSdFuWQBWd.png" /></figure><p>The core of our Flickr image loading approach is a GenreArt component. It uses local state and componentDidMount to search Flickr when it renders.</p><p>Yes, we said we’re using Redux in this app. No, we don’t need Redux for <em>everything</em>. Nobody outside this little component cares which image is rendered. Just that there’s an image. Adding Redux to this flow would complicate our code.</p><p>You can see how complicated that stuff gets in my <a href="https://school.shoutem.com/lectures/chat-app-firebase-redux-react-native/">Redux Chat App tutorial</a>. Loading states, pre loading states, post loading states. So much work.</p><p>Our GenreArt component does it all in 16 lines of code contained in a single file.</p><pre>// src/GenreArt.js<br><br>import Flickr from &#39;./flickrHelper&#39;;<br><br>export default class GenreArt extends Component {<br>    state = {<br>        uri: null<br>    }<br><br>    componentDidMount() {<br>        Flickr(this.props.name).then(uri =&gt; this.setState({ uri }));<br>    }<br><br>    render() {<br>        const { uri } = this.state;<br><br>        return uri<br>             ? (&lt;Image source={{uri: uri}} styleName=&quot;medium-wide&quot; /&gt;)<br>             : (&lt;View style={{paddingTop: 85}} /&gt;);<br>    }<br>}</pre><p>Component state starts with an empty uri. We call Flickr() with the genre name in componentDidMount, and update state when the promise resolves.</p><p>In render, we check the uri. If it exists, we render an image, if it doesn’t, we render an empty square.</p><h3>Talking to Flickr</h3><p>While Flickr does have a JavaScript SDK, it doesn’t work with React Native. It uses a lot of Node’s internal APIs and I was unable to get it working with <a href="https://github.com/mvayngrib/rn-nodeify">rn-nodeify</a>.</p><p>So we hacked our own mini library. It has a single call — search.</p><pre>// src/flickrHelper.js<br><br>export default Flickr = function (search) {<br>    return fetch(<br>        `https://api.flickr.com/services/rest/?method=flickr.photos.search&amp;format=json&amp;nojsoncallback=true&amp;api_key=8dacb3c2a9b8ff4016fab4a76df1441c&amp;license=1&amp;safe_search=1&amp;content_type=1&amp;text=${search} music`<br>    ).then(res =&gt; res.json())<br>     .then(json =&gt; new Promise((resolve, reject) =&gt; {<br>         const { farm, server, id, secret } = json.photos.photo[Math.round(Math.random()*10)];<br>         resolve(`https://farm${farm}.staticflickr.com/${server}/${id}_${secret}_z.jpg`);<br>     }));<br>};</pre><p>Hacky? Yes. Works tho.</p><p>You should make your own <a href="https://www.flickr.com/services/api/">Flickr Developer Account</a> and get an api_key. Mine’s embedded in the URL above because I don’t mind if you use it, but be nice.</p><p>Our mini library:</p><ul><li>issues a Flickr API image search using ${genre} music as the query</li><li>limits the search to Creative Commons images</li><li>parses the responses as a JSON blob</li><li>takes a random top 10 image</li><li>constructs the <a href="https://www.flickr.com/services/api/misc.urls.html">direct image URL</a></li><li>returns it by resolve-ing the promise</li></ul><p>That gives us one “album” art for one genre. To make a scrollable grid, we use <a href="http://shoutem.github.io/docs/ui-toolkit/components/grid-view">Shoutem’s GridView</a> component.</p><h3>GridView for a grid of images</h3><p>We build our grid view as a Genres component.</p><pre>// src/Genres.js<br><br>class Genres extends Component {<br>    renderRow(rowData, sectionId, index) {<br>        const cellViews = rowData.map((genre, id) =&gt; (<br>            &lt;GenreButton key={id} genre={genre} /&gt;<br>        ));<br><br>        return (<br>            &lt;GridRow columns={2}&gt;<br>                {cellViews}<br>            &lt;/GridRow&gt;<br>        )<br>    }<br><br>    render() {<br>        const groupedGenres = GridRow.groupByRows(this.props.genres, 2);<br><br>        return (<br>            &lt;ListView data={groupedGenres}<br>                      renderRow={this.renderRow} /&gt;<br>        )<br>    }<br>}</pre><p>Shoutem’s GridViews are built as a ListView special case. We start with a ListView, which gives us scrolling and rows. Then we render each row as a grid of columns.</p><p>With this approach, we can have change the number of columns in each row. A large header followed by a grid is common, for instance.</p><p>To achieve this we return a ListView from our render method. It takes our data, which is a list of grouped genres, and a renderRow method.</p><p>The renderRow method is where we return a GridView with 2 columns. Inside, we iterate through genres in this row and return a GenreButton component for each.</p><h4>GenreButton</h4><p>Each GenreButton is a Redux-connected component that renders a square with GenreArt and some text. When the genre is playing, it renders the “Playing so and so” text.</p><pre>// src/Genres.js<br><br>const GenreButton = connect(<br>    (state) =&gt; ({<br>        currentlyPlaying: state.currentlyPlaying<br>    })<br>)(({ genre, currentlyPlaying, dispatch }) =&gt; (<br>    &lt;TouchableOpacity styleName=&quot;flexible&quot; onPress={() =&gt; dispatch(playGenre(genre))}&gt;<br>        &lt;View&gt;<br>            &lt;Card styleName=&quot;flexible&quot;&gt;<br>                {currentlyPlaying.id === genre.id ? &lt;Playing /&gt; : &lt;GenreArt name={genre.name} /&gt;}<br>                &lt;Subtitle numberOfLines={1}&gt;{genre.name}&lt;/Subtitle&gt;<br>            &lt;/Card&gt;<br>        &lt;/View&gt;<br>    &lt;/TouchableOpacity&gt;<br>));</pre><p>Our GenreButton component takes currentlyPlaying from the Redux store and renders the appropriate view.</p><p>Either something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/0*IQhzxIL_kXJdSQ5p.png" /></figure><p>Or something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*OPFLZkpxaVhZnLgu.png" /></figure><p>The onPress callback dispatches a playGenre Redux action. More about our Redux setup in the next section. If you’re new to Redux, you can read my <a href="https://school.shoutem.com/lectures/chat-app-firebase-redux-react-native/#redux_101">Redux 101 chapter</a> from a few apps ago.</p><p>But before we get there, we still need our App component.</p><h3>App component holds things together</h3><p>As usual, our App component is a glorified container. It sets up a Redux store, renders a header, and fills the rest with the Genres component.</p><p>There are 3 pieces.</p><p><strong>1:</strong><br> // src/index.js const Radio = () =&gt; ( &lt;Image source={require(&#39;./media/radio.png&#39;)} style={{width: 64, height: 64 }} /&gt; );</p><p>Radio is part of the header. This unnecessary and gorgeous icon right here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*aQ1ULeCXwXVcLN7Q.png" /></figure><p><strong>2:</strong></p><p>Then we have the AppUI component. Connects to Redux to get a list of available genres and renders the UI.</p><pre>// src/index.js<br><br>const AppUI = connect(<br>    (state) =&gt; ({<br>        genres: state.genres<br>    })<br>)(({ genres }) =&gt; (<br>    &lt;Screen&gt;<br>        &lt;NavigationBar centerComponent={&lt;Radio /&gt;} /&gt;<br><br>        &lt;View style={{paddingTop: 80}}&gt;<br>            &lt;Heading styleName=&quot;h-center&quot;&gt;<br>                What do you feel like?<br>            &lt;/Heading&gt;<br><br>            &lt;Genres genres={genres} /&gt;<br>        &lt;/View&gt;<br>    &lt;/Screen&gt;<br>));</pre><p>NavigationBar is an <a href="http://shoutem.github.io/docs/ui-toolkit/components/navigation-bar">interesting Shoutem UI component</a>. I haven’t fully explored what it can do yet, but looks like something most apps need: A title, a hamburger, and an icon.</p><p>We use it to show a boombox</p><p><strong>3:</strong></p><pre>// src/index.js<br><br>const store = createStore(<br>    rootReducer,<br>    applyMiddleware(<br>        thunkMiddleware,<br>        createLogger()<br>    )<br>);<br><br>class App extends Component {<br>    render() {<br>        return (<br>            &lt;Provider store={store}&gt;<br>                &lt;AppUI /&gt;<br>            &lt;/Provider&gt;<br>        )<br>    }<br>}</pre><p>We set up a store using our rootReducer and some Redux middleware. Logger gives us insight into what’s happening, and thunks give us asynchronous Redux actions.</p><p>The App component itself renders a Provider with an AppUI. If I’m not mistaken, that puts store in a <a href="https://facebook.github.io/react/docs/context">React context</a> and makes it globally available.</p><h3>Detecting taps and loading SoundCloud songs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9y7LCfE0y7dwwF97.png" /></figure><p>You’ve made it to the “SoundCloud &amp; Redux stuff” section. That means you have a working UI and just have to wire up the Redux stuff. Huzzah!</p><h3>Redux reducer</h3><p>Let’s start with our reducer, the brains of the operation. Reducers dictate how our state changes in response to actions.</p><pre>// src/reducer.js<br><br>const rootReducer = (state = initialState, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;PLAYING_GENRE&#39;:<br>            return Object.assign({}, state,<br>                                 {<br>                                     currentlyPlaying: action.genre<br>                                 });<br>        case &#39;FOUND_SONGS&#39;:<br>            const { songs, genre } = action;<br>            return Object.assign({}, state,<br>                                 {<br>                                     songs: Object.assign({}, state.songs,<br>                                                          {<br>                                                              [genre.id]: songs<br>                                                          })<br>                                 })<br>        default:<br>            return state;<br>    }<br>};</pre><p>Our rootReducer starts with an initalState and returns state by default:. If we’re responding to the PLAYING_GENRE action, we set the currentlyPlaying property. When responding to FOUND_SONGS, we add an object to the songs property.</p><p>This approach enables us to cache song lists in the future. Loading songs doesn’t remove previously loaded songs. Unless they’re for the same genre.id of course. With some care, we can avoid pinging the SoundCloud API, if songs for a genre have already been loaded.</p><p>Now, the way we do this songs thing is un-kosher. We’re changing a deep property of an object, which means we should make a new reducer and combine them.</p><p>Meh. For a small app this is fine too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*7TOq7-BDStCpwjcS.png" /></figure><p>Our initialState looks like a long list of genres and a bunch of nulls.</p><pre>// src/reducer.js<br><br>const initialState = {<br>    genres: [&quot;Alternative Rock&quot;, &quot;Ambient&quot;, &quot;Classical&quot;, &quot;Country&quot;, &quot;EDM&quot;,<br>             &quot;Dancehall&quot;, &quot;Deep House&quot;, &quot;Disco&quot;, &quot;Drum &amp; Bass&quot;, &quot;Dubstep&quot;, &quot;Electronic&quot;,<br>             &quot;Folk&quot;, &quot;Singer-Songwriter&quot;, &quot;Rap&quot;, &quot;House&quot;, &quot;Indie&quot;, &quot;Jazz &amp; Blues&quot;,<br>             &quot;Latin&quot;, &quot;Metal&quot;, &quot;Piano&quot;, &quot;Pop&quot;, &quot;R&amp;B &amp; Soul&quot;, &quot;Reggae&quot;, &quot;Reggaeton&quot;,<br>             &quot;Rock&quot;, &quot;Soundtrack&quot;, &quot;Techno&quot;, &quot;Trance&quot;, &quot;Trap&quot;, &quot;Triphop&quot;].map(<br>                 (name, i) =&gt; ({<br>                     id: i,<br>                     name<br>                 })<br>             ),<br>    currentlyPlaying: {<br>        id: null,<br>        name: null<br>    },<br>    songs: {}<br>};</pre><p>Make sense? List genres that we want to use, set currentlyPlaying to nope, and initiate an empty songs object.</p><h3>Redux actions</h3><p>To drive our reducer and talk to our UI, we need 3 Redux actions: playingGenre, playGenre, and foundSongs.</p><p>They go in the actions.js file and look like this:</p><pre>// src/actions.js<br>import { search } from &#39;./soundcloudHelper&#39;;<br><br>export const playingGenre = (genre) =&gt; ({<br>    type: &#39;PLAYING_GENRE&#39;,<br>    genre<br>});<br><br>export const playGenre = (genre) =&gt; {<br>    return function (dispatch) {<br>        dispatch(playingGenre(genre));<br><br>        search(genre.name)<br>          .then(result =&gt; {<br>              dispatch(foundSongs(result.collection, genre));<br>          });<br>    }<br>};<br><br>export const foundSongs = (songs, genre) =&gt; ({<br>    type: &#39;FOUND_SONGS&#39;,<br>    songs,<br>    genre<br>});</pre><p>playingGenre says that something is playing right now. It tells the reducer what is playing.</p><p>playGenre is the smart action, a <a href="https://github.com/gaearon/redux-thunk">redux thunk</a> in fact. It dispatches the playingGenre action, uses search() to talk to SoundCloud, then dispatches foundSongs with the results.</p><p>foundSongs says that songs have been found. It tells the reducer which songs and which genre they belong to.</p><p>And now the fun part: Hacking the SoundCloud API without an API key.</p><h3>Talking to SoundCloud</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*G4GaXtvW6y5ksJdA." /></figure><p>Before we continue, I should say that I do not condone hacking in the “access without permission” definition. What we’re doing here is on the edge.</p><p>We’re circumventing SoundCloud’s official API access because they are slow to issue keys. I used their <a href="https://developer.soundcloud.com/">developer portal</a> to register an app, but it’s going to take them up to a month to reply.</p><p>Until then, here’s how I got around the problem.</p><p>We’re using SoundCloud’s own API key. The one they use to drive <a href="https://soundcloud.com/">search on their website</a>. I found it by performing a search and looking at the Network tab in Chrome Dev Tools.</p><p>This key should give us access to all public methods that we need: search and stream.</p><p>We’re going to make sure to attribute all songs to their respective artists and SoundCloud as a platform. Because we’re not savages. Also because it’s in the ToS.</p><p>Oh and SoundCloud’s official JavaScript SDK doesn’t work in React Native. Assumes there’s a document object. So we have to make a helper just like we did for Flickr.</p><p>Like this:</p><pre>// src/soundcloudHelper.js<br><br>const SC_KEY = &#39;2t9loNQH90kzJcsFCODdigxfp325aq4z&#39;;<br><br>export const search = (query, limit = 10, page = 0) =&gt; {<br>    return fetch(<br>        `https://api-v2.soundcloud.com/search/tracks?q=${query}&amp;client_id=${SC_KEY}&amp;limit=${limit}&amp;offset=${page*limit}&amp;linked_partitioning=1`<br>    ).then(res =&gt; res.json())<br>     .then(json =&gt; new Promise((resolve, reject) =&gt; {<br>         resolve(json);<br>     }));<br>};<br><br>export const streamUrl = (trackUrl) =&gt; `${trackUrl}/stream?client_id=${SC_KEY}`;</pre><p>The search function makes a fetch() call to SoundCloud’s API, parses the response as a JSON blob, and resolves a new Promise with the json data. I’m not entirely sure that last Promise is needed .</p><p>SoundCloud search returns songs with a bunch of properties. We’re going to explore those in Part 2 of this tutorial. Don’t forget to <a href="http://eepurl.com/cxTnOL">subscribe so you don’t miss it</a>.</p><p>The one we cared about <a href="https://www.youtube.com/watch?v=mQ9OHvvONTo">during livecoding</a> is trackUrl. It gives us a direct link to a song, which we convert into a direct streamUrl with some additions.</p><p>We used it to try setting up <a href="https://github.com/tlenclos/react-native-audio-streaming">react-native-audio-streaming</a>, which didn’t quite work out. Yet.</p><h3>Working music app part 1</h3><p>If you’ve been following along, you should now have a working music app. It doesn’t yet play music, but it lets you pick a genre, finds a song to play, and tells you which song it would play if it could play a song.</p><p>That’s almost as good, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*QjybwEVhpulLZ77_.gif" /></figure><p>If it didn’t work, check out the <a href="https://github.com/shoutem/school/tree/48b6afa4bdf6894375cdba698f13dc32a3094e7c/MusicApp">full source code on GitHub</a>.</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/build-react-native-music-app-tutorial-part1/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=292b31b7d002" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/build-a-react-native-music-app-tutorial-part-1-react-native-school-292b31b7d002">Build a React Native Music App tutorial, part 1 — React Native School</a> was originally published in <a href="https://medium.com/react-native-development">React Native Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>