<?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[Stories by Shoutem on Medium]]></title>
        <description><![CDATA[Stories by Shoutem on Medium]]></description>
        <link>https://medium.com/@shoutem?source=rss-690194f3df50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l_fg8WWKoDTBfvnbG9N8iQ.png</url>
            <title>Stories by Shoutem on Medium</title>
            <link>https://medium.com/@shoutem?source=rss-690194f3df50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:35:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shoutem/feed" 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: 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-690194f3df50------2</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>Fri, 11 Aug 2017 12:43:33 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%2Fwww.youtube.com%2Fembed%2FpZI62EwsyHo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpZI62EwsyHo&amp;image=https%3A%2F%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-690194f3df50------2</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 13:31:29 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%2Fwww.youtube.com%2Fembed%2FkCLaRgFi0wg%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkCLaRgFi0wg&amp;image=https%3A%2F%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-690194f3df50------2</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 07:34:09 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%2Fwww.youtube.com%2Fembed%2FiMt4Xdsafvw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiMt4Xdsafvw&amp;image=https%3A%2F%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-690194f3df50------2</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 14:19:43 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%2Fwww.youtube.com%2Fembed%2FFcf-tgSI3x0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFcf-tgSI3x0&amp;image=https%3A%2F%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[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-690194f3df50------2</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:13:47 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%2Fwww.youtube.com%2Fembed%2FuqnFEcrbnsA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuqnFEcrbnsA&amp;image=https%3A%2F%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>
        <item>
            <title><![CDATA[React Native camera app with live preview saturation and brightness filters]]></title>
            <link>https://medium.com/react-native-development/react-native-camera-app-with-live-preview-saturation-and-brightness-filters-d34535cc6d14?source=rss-690194f3df50------2</link>
            <guid isPermaLink="false">https://medium.com/p/d34535cc6d14</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webgl]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Thu, 27 Apr 2017 12:55:08 GMT</pubDate>
            <atom:updated>2017-04-27T12:55:28.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iON5KUipLBs5iN9Ain6mQ.png" /></figure><p>Today we’re building a camera app that uses WebGL for live preview saturation and brightness filters. It’s like, Instagram but not.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fqc-2adSgcno%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dqc-2adSgcno&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fqc-2adSgcno%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/36727528cb467234c98f4c83dcedfdae/href">https://medium.com/media/36727528cb467234c98f4c83dcedfdae/href</a></iframe><p>Today we’re building a camera app with live preview saturation and brightness filters. It’s like, Instagram but not. There’s no “Take Pic” button. You have to take a screenshot. But filters!</p><p>You can turn it into an Instagram with these helpful <a href="https://github.com/stoffern/gl-react-instagramfilters">WebGL shaders</a> that @stoffern build. Oh yes, we’re using WebGL to manipulate camera output</p><p>In this lesson you will learn:</p><ul><li>how to use the camera with <a href="https://github.com/lwansbrough/react-native-camera">react-native-camera</a></li><li>how to do WebGL with <a href="https://github.com/gre/gl-react">gl-react</a></li><li>rudimentary gesture detection with <a href="https://facebook.github.io/react-native/docs/panresponder.html">PanResponder</a></li></ul><p>We’re building the app in five steps. You can see its <a href="https://github.com/shoutem/school/tree/master/LiveInstagram">finished source on Github</a>.</p><p>Wanna build a new app every two weeks? <a href="http://eepurl.com/cxTnOL">Subscribe by email</a>.</p><h3>Step 0: Prep work</h3><p>After running $ react-native init LiveInstagram, we need to do some prep. I think this is going to be the standard approach going forward … maybe I should make a boilerplate</p><p>But boilerplates are a trap. For the maintainer.</p><p>Here’s what you do:</p><p><strong>1.</strong> Install Shoutem UI toolkit with $ react-native install @shoutem/ui. We’ll make light use of it in this lesson, but I’ve gotten used to having it available 🙂</p><p><strong>2.</strong> Clean out index.ios.js. When you’re done, it should look like this:</p><pre>// index.ios.js<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/App&#39;;<br><br>AppRegistry.registerComponent(&#39;LiveInstagram&#39;, () =&gt; App);</pre><p>You can do the same with index.android.js, if you prefer to work on Android. I focus on iOS because I don’t have an Android device.</p><p><strong>3.</strong> Create a src/ directory for all our code.</p><p><strong>4.</strong> Make an App.js file with our base component. Something like this for now:</p><pre>// src/App.js<br><br>import React, { Component } from &#39;react&#39;;<br>import { Screen } from &#39;@shoutem/ui&#39;;<br><br>export default class App extends Component {<br>    render() {<br>        &lt;Screen /&gt;<br>    }<br>}</pre><p>The benefit of moving all our code into src/App and gutting index.*.js is that it’s easier to share code between both platforms. Our LiveInstagram app doesn’t follow UI conventions of either platform, so we might as well use the same code for both.</p><h3>Step 1: Camera app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N9CpZpt07_IbqUFx.png" /></figure><p>We start with a basic camera app. Asks for camera permissions, shows a live preview of your camera.</p><p>Thanks to the <a href="https://github.com/lwansbrough">@lwansbrough</a>‘s great work on <a href="https://github.com/lwansbrough/react-native-camera">react-native-camera</a>, this part is simple. After <a href="https://school.shoutem.com/lectures/add-serverless-firebase-push-notifications-react-native-app-chat-app-part-2/">last week’s Firebase fiasco</a>, I walked into this project expecting the worst.</p><p>Camera stuff was the easiest.</p><p><strong>1.</strong> Install with $ react-native install react-native-camera</p><p><strong>2.</strong> Set up asking for permissions inside Info.plist.</p><pre>./ios/LiveInstagram/Info.plist<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>  &lt;dict&gt;<br>  ...<br>    &lt;key&gt;NSCameraUsageDescription&lt;/key&gt;<br>    &lt;string&gt;We need your beautiful camera&lt;/string&gt;<br>    &lt;key&gt;NSPhotoLibraryUsageDescription&lt;/key&gt;<br>    &lt;string&gt;We&#39;re only saving to temp, promise&lt;/string&gt;<br>  &lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>We need a permission to use the camera <em>and</em> a permission to save photos to the library. We don’t <em>save</em> any photos so asking for library permissions sucks, but we need it to access temp.</p><p>react-native-camera used to allow taking pictures straight to memory, but that’s been deprecated. I don’t know why.</p><p><strong>3.</strong> Render the camera view in App</p><pre>// src/App.js<br>import Camera from &#39;react-native-camera&#39;;<br><br>export default class App extends Component {<br>    render() {<br>        return (<br>            &lt;Screen&gt;<br>                &lt;Camera style={{flex: 1}}<br>                        ref={cam =&gt; this.camera=cam}<br>                        aspect={Camera.constants.Aspect.fill}&gt;<br>                    <br>                &lt;/Camera&gt;<br>            &lt;/Screen&gt;<br>        );<br>    }<br>}</pre><p>We add &lt;Camera&gt; to our main render method. flex: 1 makes it fill the screen, a fill aspect ratio ensures it looks nice. We’ll use this.camera later to access the camera instance and capture photos.</p><p>Run the app on your phone with XCode and you’ll see what your phone can see. I love how easy that was. Thanks @lwansbrough.</p><h3>Step 2: Render a WebGL test component</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Ek8AxYmpCUf-_R2.png" /></figure><p>Now that we have a camera, we need to set up the WebGL component. It’s going to overlay the camera view with a GPU-rendered view with changed brightness and saturation.</p><p>We’re using <a href="https://github.com/gre/gl-react">gl-react v3 alpha</a> by <a href="https://github.com/gre">@gre</a> and I have no idea how it works. I know it’s the WebGL API, but it runs on native code so it can’t be WebGL actually.</p><p>I’m happy the abstraction is so good that I don’t need to know how stuff works underneath ☺️</p><p><strong>1.</strong> We have to install gl-react and gl-react-native. Make sure you have the next version because the old 2.x doesn’t work well. v3 is a complete rewrite.</p><pre>$ react-native install gl-react@next<br>$ react-native install gl-react-native@next</pre><p><strong>2.</strong> Our WebGL Surface needs to know how big it is, so we have to keep track of width and height ourselves. We can do that with an onLayout callback on our Screen component and some local state.</p><pre>// src/App.js<br><br>export default class App extends Component {<br>    state = {<br>        width: null,<br>        height: null<br>    }<br><br>    onLayout = (event) =&gt; {<br>        const { width, height } = event.nativeEvent.layout;<br><br>        this.setState({<br>            width,<br>            height<br>        });<br>    }<br>    <br>    render() {<br>        const { width, height } = this.state;<br><br>        if (width &amp;&amp; height) {<br>            return (<br>                &lt;Screen onLayout={this.onLayout}&gt;<br>                        // ...<br>                &lt;/Screen&gt;<br>            );<br>       }else{<br>            return (<br>                &lt;Screen onLayout={this.onLayout} /&gt;<br>            );<br>        }<br>    }<br>}</pre><p>onLayout is called every time our app re-layouts. We use the callback to read the new width and height, and save them to this.state.</p><p><strong>3.</strong> We render the WebGL Surface <em>inside</em> the Camera component. This lets us overlay the Camera view, which is great. We’re rendering opaque things so the Camera is invisible anyway, which is wasteful.</p><pre>// src/App.js<br><br>import { Surface } from &quot;gl-react-native&quot;;<br><br>import Saturate from &#39;./Saturate&#39;;<br><br>export default class App extends Component {<br>    // ...<br>    <br>    render() {<br>        // ...<br>        <br>        const filter = {<br>        contrast: 1,<br>        saturation: 1,<br>        brightness: 1<br>        }<br>        <br>        &lt;Camera style={{flex: 1}}<br>            ref={cam =&gt; this.camera=cam}<br>            aspect={Camera.constants.Aspect.fill}&gt;<br><br>        &lt;Surface style={{ width, height }}&gt;<br>            &lt;Saturate {...filter}&gt;<br>                {{ uri: &quot;https://i.imgur.com/uTP9Xfr.jpg&quot; }}<br>            &lt;/Saturate&gt;<br>        &lt;/Surface&gt;<br><br>    &lt;/Camera&gt;<br>    <br>    // ...<br>    }<br>}</pre><p>You can think of Surface as a canvas component. It’s a region where you render WebGL nodes. Every Surface needs at least one Node child.</p><p>Saturate is a Node component. It renders an image and adjusts its contrast, saturation, and brightness.</p><p><strong>4.</strong> The code for Saturate comes from a <a href="https://gl-react-cookbook.surge.sh/saturation">gl-react example</a> because I don’t understand GL shader code enough to write my own.</p><pre>// src/Saturation.js<br>//@flow<br>import React, { Component } from &quot;react&quot;;<br>import { Shaders, Node, GLSL } from &quot;gl-react&quot;;<br><br>const shaders = Shaders.create({<br>  Saturate: {<br>    frag: GLSL`<br>precision highp float;<br>varying vec2 uv;<br>uniform sampler2D t;<br>uniform float contrast, saturation, brightness;<br>const vec3 L = vec3(0.2125, 0.7154, 0.0721);<br>void main() {<br>  vec4 c = texture2D(t, uv);<br>    vec3 brt = c.rgb * brightness;<br>    gl_FragColor = vec4(mix(<br>    vec3(0.5),<br>    mix(vec3(dot(brt, L)), brt, saturation),<br>    contrast), c.a);<br>}<br>`<br>  }<br>});<br><br>const Saturate = ({ contrast, saturation, brightness, children }) =&gt; (<br>    &lt;Node shader={shaders.Saturate}<br>          uniforms={{ contrast, saturation, brightness, t: children }} /&gt;<br>);<br><br>export default Saturate;</pre><p>Here’s what I do understand: For gl-react we define shaders statically. Each comes as a GLSL language blob and goes into a big Shaders dictionary.</p><p>I don’t understand the GLSL language yet. I know main() is called on every pixel, I know this code runs on the GPU, and I know that it looks a lot like C code. It also looks like it’s based on vector mathematics and matrix composition.</p><p>We’re setting our base image as a texture, I think. texture2D sure implies that much.</p><p>The Saturate component itself renders a Node, which takes a shader and something called uniforms. I’m not sure what those are, but it looks like they could be arguments for the GLSL code.</p><h3>Step 3: Feed camera data into WebGL view</h3><p>Great, we have a WebGL-rendered static image with funky saturation, and a live camera view hiding underneath. If that sounds bad performance-wise, wait ’till you see what happens next</p><p>We take a photo every 5 milliseconds, save it to a temp location, and update the WebGL view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*OSpotdCk7sFJSPlj.gif" /></figure><p>I came up with 5ms experimentally. It looks smooth and, with some tweaks to image quality, keeps the app from crashing for almost a whole minute. Yes, the app crashes. Yes, it’s bad. No, I don’t know [yet] how to fix it. Maybe someone will tell me in the comments</p><p><strong>1.</strong> We start a timer in onLayout because we want to be sure this.camera exists. We’re rendering Camera only after we have width/height, remember.</p><pre>// src/App.js<br>class App {<br>    // ...<br>    <br>    onLayout = (event) =&gt; {<br>        // ..<br>        this.start();<br>    }<br><br>    refreshPic = () =&gt; {<br>        // pic taking<br>    }<br><br>    start() {<br>        this.timer = setInterval(() =&gt; this.refreshPic(),<br>                                 5);<br>    }<br><br>    onComponentWillUnmount() {<br>        clearInterval(this.timer);<br>    }</pre><p>onLayout calls start, which sets an interval running every 5 milliseconds. We make sure to stop the interval in onComponentWillUnmount.</p><p><strong>2.</strong> Thanks to <a href="https://github.com/lwansbrough">@lwansbrough</a>, taking a pic is as easy as rendering a camera preview was.</p><pre>// src/App.js<br><br>class App {<br>    // ...<br>    refreshPic = () =&gt; {<br>        this.camera<br>            .capture({<br>                target: Camera.constants.CaptureTarget.temp,<br>                jpegQuality: 70<br>            })<br>            .then(data =&gt; this.setState({<br>                path: data.path<br>            }))<br>            .catch(err =&gt; console.error(err));<br>    }</pre><p>We call .capture on this.camera, tell it to use 70% jpeg quality and to save images to a temporary location. Saving is necessary because direct-to-memory went away in a recent version of react-native-camera. This is the part that requires library access permissions on iOS.</p><p>When the promise resolves, we get a path to the local image, and save it to local state. If there’s an error, we cry.</p><p><strong>3.</strong> Our camera preview is invisible. Turning it off would save resources and might even convince our app not to crash. But I couldn’t figure out how to do that. Reducing output quality is the next best thing.</p><p>Add captureQuality to &lt;Camera&gt; in render. Like this:</p><pre>// src/App.js<br><br>class App {<br>    // ...<br>    &lt;Camera style={{flex: 1}}<br>            ref={cam =&gt; this.camera=cam}<br>            captureQuality={Camera.constants.CaptureQuality[&quot;720p&quot;]}<br>            aspect={Camera.constants.Aspect.fill}&gt;</pre><p>You can play with values in the filter constant to see how they affect the image.</p><h3>Step 4: Basic gesture recognition</h3><p>React Native comes with a built-in class to detect user gestures — <a href="https://facebook.github.io/react-native/docs/panresponder.html">PanResponder</a>. I don’t know why it’s called that.</p><p>We can use it to detect which direction a user is dragging on the screen. The API it offers is pretty low-level so there’s some manual work involved in figuring out the user’s intentions.</p><p>The basics go like this:</p><p><strong>1.</strong> Start a PanResponder instance in componentWillMount.</p><pre>// src/App.js<br><br>class App {<br>    // ...<br>    <br>    componentWillMount() {<br>        this._panResponder = PanResponder.create({<br>            onMoveShouldSetResponderCapture: () =&gt; true,<br>            onMoveShouldSetPanResponderCapture: () =&gt; true,<br><br>            onPanResponderGrant: (e, {x0, y0}) =&gt; {<br>                // start gesture<br>            },<br><br>            onPanResponderMove: (e, {dx, dy}) =&gt; {<br>                // gesture progress<br>            },<br><br>            onPanResponderRelease: (ev, {vx, vy}) =&gt; {<br>                // gesture complete<br>            }<br>        });<br>    }</pre><p>We create a new PanResponder instance and assign it to this._panResponder. To make it work, we define a bunch of callbacks.</p><p>onPanResponderGrant is called when a gesture begins, we’ll use it to initialize our tracking code. onPanResponderMove is where we’re going to track movement and update saturation/brightness, and onPanResponderRelease is where we can give the user some “done” feedback. We’re not going to need this.</p><p><strong>2.</strong> We attach our pan responder to the main app view like this:</p><pre>// src/App.js<br><br>class App {<br>    // ...<br>    render() {<br>        const { width, height } = this.state;<br><br>        if (width &amp;&amp; height) {<br>            return (<br>                &lt;Screen onLayout={this.onLayout}<br>                        {...this._panResponder.panHandlers}&gt;<br>                   // ..<br>        }else{<br>            return (<br>                &lt;Screen onLayout={this.onLayout} /&gt;<br>            );<br>        }<br>    }<br>}</pre><p>It’s that {...this._panResponder.panHandlers} part. I expect you can add gesture recognition like this to any React Native element. Neat, huh?</p><h3>Step 5: Control saturation/brightness through gestures</h3><p>Time to wire everything up. We’re going to move filter into local state and manipulate it in our pan handler.</p><p><strong>1.</strong> We move filter into local state like this</p><pre>// src/App.js<br><br>class App {<br>    state = {<br>        width: null,<br>        height: null,<br>        path: &quot;https://i.imgur.com/uTP9Xfr.jpg&quot;,<br>        contrast: 1,<br>        brightness: 1,<br>        saturation: 1<br>    }<br><br>        // ...<br>        <br>        render() {<br>        const { width, height, brightness, contrast, saturation } = this.state;<br><br>        const filter = {<br>            brightness,<br>            contrast,<br>            saturation<br>        }<br>        <br>        // ..<br>    }<br>}</pre><p>That part was quick. Instead of using magic values in const filter =, we take them out of this.state.</p><p><strong>2.</strong> We initialize our starting state when the gesture begins. We’ll use D3 linear scales to help us with the maths of <em>“how much did the user drag and what does that mean for brightness”</em>.</p><p>Run $ react-native install d3-scale. No need for the whole D3 library, the scales will do.</p><p>You can think of a linear scale as a linear function from middle school maths. It maps values from a domain, to values in a range.</p><pre>// src/App.js<br><br>import { scaleLinear } from &#39;d3-scale&#39;;<br><br>class App {<br>    // ...<br>    dragScaleX = scaleLinear()<br>    dragScaleY = scaleLinear()<br><br>    componentWillMount() {<br>        // ...<br>            onPanResponderGrant: (e, {x0, y0}) =&gt; {<br>                const { width, height } = this.state;<br><br>                this.dragScaleX<br>                    .domain([-x0, width-x0])<br>                    .range([-1, 1]);<br><br>                this.dragScaleY<br>                    .domain([-y0, height-y0])<br>                    .range([1, -1]);<br>            },<br>            <br>            // ...<br>        });<br>    }</pre><p>When a gesture starts, we initialize our dragScaleX and dragScaleY with a new domain and range. The range goes from -1 to 1 because we’re adding it to the default value of 1. 0 to 2 should give us a full range for saturation and brightness.</p><p>The domain is trickier. We want the screen to represent a full range. All the way up, brightness is at 2, all the way down, it’s 0, middle is 1.</p><p>But we only get drag distance inside onPanResponderMove, so we have to set our domains based on start position. If we start at x0 that means we’ll reach the left edge of the screen when we drag in the negative direction by a whole x0. That’s -x0. In the other direction, we have width-x0 of space before hitting the edge.</p><p>That makes our domain [-x0, width-x0]. Similarly for the vertical axis: [-y0, height-y0].</p><p><strong>3.</strong> We use these scales to change brightness and saturation in onPanResponderMove. Like this:</p><pre>// src/App.js<br><br>import { scaleLinear } from &#39;d3-scale&#39;;<br><br>class App {<br>    // ...<br><br>    componentWillMount() {<br>        // ...<br>            onPanResponderMove: (e, {dx, dy}) =&gt; {<br>                this.setState({<br>                    saturation: 1 + this.dragScaleX(dx),<br>                    brightness: 1 + this.dragScaleY(dy)<br>                });<br>            },<br>            <br>            // ...<br>        });<br>    }</pre><p>We take drag distance on both axes, translate it into the [-1, 1] range using the scales, and update local state with this.setState.</p><p>This triggers a re-render, updates the WebGL view, and shows the user an updated preview. Fast enough to feel responsive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*m-6GnJpjcYXxjEzr.gif" /></figure><p>Wanna build a new app every two weeks? <a href="http://eepurl.com/cxTnOL">Subscribe by email</a>.</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/react-native-camera-app-live-preview-saturation-brightness-filters/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d34535cc6d14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/react-native-camera-app-with-live-preview-saturation-and-brightness-filters-d34535cc6d14">React Native camera app with live preview saturation and brightness filters</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[Add serverless Firebase push notifications to your React Native app — Chat App, part 2]]></title>
            <link>https://medium.com/react-native-development/add-serverless-firebase-push-notifications-to-your-react-native-app-chat-app-part-2-8ff1bbc6c479?source=rss-690194f3df50------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ff1bbc6c479</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Tue, 11 Apr 2017 14:00:57 GMT</pubDate>
            <atom:updated>2017-04-11T14:01:41.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esHXOEeX4I-8NhuVzty-mA.png" /></figure><p>That was the hardest thing in coding that I’ve ever done. Setting up Firebase Cloud Messaging with a React Native app in March/April 2017 is hell. I hope the ecosystem improves.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXxKdVjYRjI8%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXxKdVjYRjI8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXxKdVjYRjI8%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5c4c9bcc01baae454343fb14b2f671/href">https://medium.com/media/6c5c4c9bcc01baae454343fb14b2f671/href</a></iframe><p>After 7 days, it works! As far as I know, this is the only comprehensive how-to out there. Enjoy 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-38yNlmlvpLYAOuR.gif" /></figure><p>Before you ask: yes, notifications fire when your app is in the background. And yes, the app fetches new messages in the background too 🙂</p><h3>Here’s what you’ll learn in today’s lecture:</h3><ul><li>how to convince Apple to let you use notifications</li><li>how to run your app on a real device</li><li>how to make React Native and Firebase native SDK get along</li><li>how to setup Firebase with your Apple certificates</li><li>how to trigger notifications with Firebase Cloud Functions</li></ul><p>Today’s lecture is part 2 of Build a Chat App <a href="https://school.shoutem.com/lectures/chat-app-firebase-redux-react-native/">with Firebase and Redux</a>. I assume you’re continuing from there and already have the base Chat App defined.</p><p>You don’t need the Chat App to follow this lecture. As long as your app is React Native first, created with react-native init, then this guide is for you.</p><p>Some of this guide is iOS specific. We’re using the platform agnostic <a href="https://github.com/evollu/react-native-fcm">react-native-fcm</a> library, so you can use most of this guide for Android as well. But I haven’t tested that because I don’t have an Android device.</p><p>That’s a lot of disclaimers … <em>basically</em> this is <strong>the only way</strong> I’ve found to implement serverless push notifications. This is also the only comprehensive guide to integrating the native Firebase SDK with React Native 0.42.x or 0.43.x. Google found nothing but random StackOverflow questions and outdated documentation</p><p>You can see the <a href="https://github.com/shoutem/school/tree/master/ChatApp">final code on Github</a>.</p><h3>Apple Developer Account</h3><p>First thing’s first: We have to pay our dues to Apple. To play with push notifications on iOS, you need an Apple Developer account. It costs $99 + tax and a day or two of waiting. You’re also going to need an iDevice because the simulator doesn’t receive push notifications.</p><p>Having an Apple Developer account lets you run apps on your phone, publish them to the app store, and things like that. I don’t know everything you can do, but it sounds like anything even advanced or proprietary requires a paid account with a confirmed identity.</p><p>They asked for a photo of my photo ID. ‍♂️</p><p>The easiest way to create a developer account is through XCode. Same process as connecting an existing account, except you click Add new account instead of picking an existing one.</p><p>Open your project’s ios/&lt;name&gt;.xcodeproj file with XCode, navigate to General settings and look for Signing config. This part videos particularly well. Watch the video at around 1min, if you’re confused.</p><p>I was very confused looking at this for the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*z-X2GOGYm3Y8XAmN.png" /></figure><p>If you don’t have a Developer Account yet, the interface will guide you through creating one. That part happens through your browser and involves</p><h3>Set up certs and enable Push Notifications on Firebase and Apple</h3><p>After you’ve got your Apple Developer Account, it’s time to set up your certificates. You need two of them: One for running your app on a device, another for push notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*jVeg9ZPfNVtKJoQv.gif" /></figure><p>Setting up certificates is annoying, I agree. But it improves app security. When notifications are signed, your app can be sure <em>you</em> sent them. When your app is signed, a device can be sure it’s <em>your</em> app.</p><p>Imagine if any random person on the internet could harass your users with notifications or publish app that look just like yours, but steal users’ info? No good, right? Hence, certificates.</p><p>The setup videos well and texts poorly. I suggest watching the video from about 2min onwards.</p><p>Here’s what you do in a nutshell:</p><ol><li>Create a certificate signing request with your Keychain App</li><li>Create an App ID in Apple Developer portal. Make sure your Bundle ID in XCode and on the site match</li><li>Create a new certificate</li><li>Pick certificate type: App Development or Push Notification</li><li>For notifications certificate, pick your App ID</li><li>Download both certificates</li><li>Double-click certificates to install in your Keychain</li></ol><h3>Create app in Firebase, add certificate</h3><p>Once you have both certificates installed locally, you have to give the Push Notifications one to Firebase. That way it can sign notifications before sending them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*VhMESHs0knPdHZ-X.png" /></figure><p>Video is your friend. 🙂 Here’s what you do in a nutshell:</p><ol><li>Find your push notification certificate in Keychain</li><li>Export into p12</li><li>Go to Firebase Console, click Add App</li><li>Make sure Bundle ID is same as in XCode</li><li>Skip config stuff for now</li><li>Go to Cloud Messaging tab in app settings</li><li>Upload Certificate</li></ol><h3>Enable Push Notifications in XCode</h3><p>So many steps! Two more 🙂</p><p>Go back to XCode, find the Capabilities tab, and enable Push Notifications. You should see two grey checkmarks. I don’t know why they’re not green, I was quite disappointed.</p><p>They’re def red when something goes wrong … so unfair.</p><p>The library we’re using — react-native-fcm — suggests enabling Keychain Sharing and Background Modes as well. I don’t know what keychain sharing does, and I think background modes lets us accept notifications when our app is in the background.</p><h3>Run your app on a device</h3><p>Press Play on top of the XCode window. Wait.</p><p>Your device should show an app. If it doesn’t … literally any of the steps above could have gone wrong. I suggest going over again slowly. Google any errors that you see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*0Xt05pvfnNLBc1tf.png" /></figure><h3>Enable Firebase SDK without exploding your app</h3><p>Now for the fun part: Installing the Firebase SDK without using CocoaPods. No matter what the various README files and documentation tell you, CocoaPods and React Native <strong><em>do not like each other</em></strong>.</p><p>I realized this after a careful process of elimination and two or three apps started from scratch. There is no sane way to get it working.</p><p>As soon as CocoaPods enters a project that was started with react-native init, the project explodes. Core React libraries become unavailable and if you start fixing imports, you will never finish. Fix one, the next one breaks.</p><p>The solution that I’ve found is to install Firebase SDK manually. Download from <a href="https://firebase.google.com/docs/ios/setup">Firebase docs</a>, then add every .framework file in Firebase/Analytics and Firebase/Messaging to your app.</p><p>Now your app has the SDK.</p><p>But it lacks two core libraries that Firebase uses. I don’t know why, but they’re libz.dylib and libsqlite3.dylib.</p><p>You can add them through the Build Phases tab in your project. They’re in /usr/lib.</p><p>¯_(ツ)_/¯</p><h3>Initialize the SDK</h3><p>For the initialization step, you’ll need to copy paste some code and the Firebase config from your console.</p><p>Go to your Firebase Console, find your app, and look for a button that says GoogleService-Info.plist. Drag it into your XCode project next to Info.plist. If you open it, you’ll see it contains Firebase authentication stuff.</p><p>You should <a href="https://github.com/shoutem/school/blob/master/ChatApp/ios/ChatApp/GoogleService-Info.plist">use mine</a>, if you want to receive notifications from the global chatroom. That’s the one everyone from this tutorial is sharing 🙂</p><p>Then go into AppDelegate.h and add an import and a parameter to the main interface.</p><pre>// AppDelegate.h<br><br>// add this<br>@import UserNotifications;<br><br>// change this with extra param<br>@interface AppDelegate : UIResponder &lt;UIApplicationDelegate,UNUserNotificationCenterDelegate&gt;</pre><p>Changes in AppDelegate.m are more extensive. You have to add an import, two lines to the application function, and a couple functions at the end of the file.</p><pre>// AppDelegate.m<br><br>// add on top<br>#import &quot;RNFIRMessaging.h&quot;<br><br>// add before return YES;<br>  [FIRApp configure];<br>  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];<br>  <br>// add before @end<br>- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler<br>{<br>  [RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];<br> }<br><br>- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler<br>{<br>     [RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];<br>}<br><br>//You can skip this method if you don&#39;t want to use local notification<br>-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {<br>  [RNFIRMessaging didReceiveLocalNotification:notification];<br>}<br><br>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{<br>   [RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];<br>}</pre><p>I would explain what all this code does, but to be honest, I don’t know. ObjectiveC is a strange foreign land to me.</p><h3>Two more files</h3><p>In the video I get an error after adding the code. That’s because I forgot to copy Firebase.h and module.modulemap from the Firebase SDK package.</p><p>You should add those too. I think they’re what defines the firebase module in the first place.</p><h3>Listen for push notifications</h3><p>That was fun … kind of. Now comes the really fun part: notifications flying around!</p><p>Back to the familiar embrace of JavaScript land. I feel more comfortable already. All that stuff we just did, that felt harder than setting up Webpack …</p><p>Anyway, the best palce to put JavaScript-side notification code is in Redux thunks. It’s code that <em>does</em> something, so I think it fits in actions or thunks.</p><p>We don’t want the notifications dialog to scare people off, but we do want them to be notified of new messages. That means we should put notification code somewhere close to the user is authorized now action.</p><p>With some code tweaks <a href="https://school.shoutem.com/lectures/chat-app-firebase-redux-react-native/">since last lecture</a>, I built a startChatting action. It finishes authorizing a user, initiates message fetching, and subscribes to notifications.</p><pre>// src/actions/index.js<br><br>import FCM, { FCMEvent,<br>              NotificationType,<br>              WillPresentNotificationResult,<br>              RemoteNotificationResult } from &#39;react-native-fcm&#39;;<br>import { Platform } from &#39;react-native&#39;;<br><br>// ...<br><br>const startChatting = function (dispatch) {<br>    dispatch(userAuthorized());<br>    dispatch(fetchMessages());<br><br>    FCM.requestPermissions();<br>    FCM.getFCMToken()<br>       .then(token =&gt; {<br>           console.log(token)<br>       });<br>    FCM.subscribeToTopic(&#39;secret-chatroom&#39;);<br><br>    FCM.on(FCMEvent.Notification, async (notif) =&gt; {<br>        console.log(notif);<br><br>        if (Platform.OS === &#39;ios&#39;) {<br>            switch (notif._notificationType) {<br>                case NotificationType.Remote:<br>                    notif.finish(RemoteNotificationResult.NewData); //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed<br>                    break;<br>                case NotificationType.NotificationResponse:<br>                    notif.finish();<br>                    break;<br>                case NotificationType.WillPresent:<br>                    notif.finish(WillPresentNotificationResult.All); //other types available: WillPresentNotificationResult.None<br>                    break;<br>              }<br>            }<br>    });<br><br>    FCM.on(FCMEvent.RefreshToken, token =&gt; {<br>        console.log(token);<br>    });<br>}</pre><p>That’s more like it! Some familiar code!</p><p>We import a bunch of stuff from react-native-fcm, and define a startChatting helper function. Thunks call startChatting and pass it the dispatch function so it can dispatch Redux actions.</p><p>Does that make it a thunk?</p><p>The important bits are:<br> — FCM.requestPermissions asks the OS for permission to show notifications, that’s the dialog where you often click No<br> – FCM.getFCMToken generates and/or receives a unique notification token for this device. It lets us send messages to specific users. Ideally you’d save this to Firebase 🙂<br> – FCM.subscribeToTopic subscribes users to the secret-chatroom channel. This makes it easy to send notifications to a group of devices.<br> – FCM.on(..., this part handles notifications when they come in.</p><p>I don’t know <em>exactly</em> why the notification handling code has to be that way, I got it from the README file. My understanding is that iOS needs us to “finish” notifications in different ways depending on their type.</p><p>Android is smart enough to handle things. I guess …</p><h3>Send notifications on DB changes using Firebase Cloud Functions</h3><p>Our app is listening for notifications. We still have to fire them, though.</p><p>Traditionally people used servers for that. You build a server, you observe data on Firebase, you use the API to send notifications. Yawn</p><p>On March 10th, 2017, Google released <a href="https://firebase.google.com/docs/functions/">Firebase Cloud Functions</a>. Supposedly a competitor to AWS Lambda, but I haven’t tried that before. The bottom line is this: You can run code without running a server.</p><p>This could almost be its own article, so here’s a quick walkthrough. <a href="https://github.com/shoutem/school/tree/master/ChatAppFirebaseFunctions">Full code on Github</a>.</p><p><strong>1:</strong> You need the firebase CLI tool. It’s in the docs</p><p><strong>2:</strong> Make a directory, ChatAppFirebaseFunctions maybe</p><p><strong>3:</strong> firebase login &amp;&amp; firebase init</p><p><strong>4:</strong> Write code</p><p>For a simple “notify everyone on new message” function, the code looks like this:</p><pre>// ChatAppFirebaseFunctions/functions/index.js<br><br>const functions = require(&#39;firebase-functions&#39;);<br>const admin = require(&#39;firebase-admin&#39;);<br>const _ = require(&#39;lodash&#39;);<br><br>admin.initializeApp(functions.config().firebase);<br><br>exports.sendNewMessageNotification = functions.database.ref(&#39;/messages&#39;).onWrite(event =&gt; {<br>    const getValuePromise = admin.database()<br>                                 .ref(&#39;messages&#39;)<br>                                 .orderByKey()<br>                                 .limitToLast(1)<br>                                 .once(&#39;value&#39;);<br><br>    return getValuePromise.then(snapshot =&gt; {<br>        console.log(_.values(snapshot.val())[0]);<br>        const { text, author } = _.values(snapshot.val())[0];<br><br>        const payload = {<br>            notification: {<br>                title: &#39;New msg&#39;,<br>                body: text,<br>                icon: author.avatar<br>            }<br>        };<br><br>        return admin.messaging()<br>                    .sendToTopic(&#39;secret-chatroom&#39;, payload);<br>    });<br>});</pre><p>We export a function that registers an onWrite listener on our list of messages. When messages are written, a push notification will fire.</p><p>There’s no need to tell anyone what our function is. If it’s exported, Firebase will figure it out. That part confused me at first.</p><p>Inside our listener, we get the last message, use it to build the notification payload, and send it to everyone subscribed to secret-chatroom. Everyone finds out when things happen and with some luck the chatroom becomes a community.</p><p><strong>5:</strong> firebase deploy</p><p>Done. Your code is available right away.</p><h3>Victory, you have serverless push notifications</h3><p>Rejoice!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*_IwLRvOsl1O2rITw.gif" /></figure><p>That … that was hard right? Am I just dumb?</p><p>Sure felt like a lot of clicking, but we’ve unlocked a new skill: notifications. So many possibilities for future apps!</p><p>You should <a href="http://eepurl.com/cxTnOL">subscribe by email</a> to get a new app walkthrough every 2 weeks. I learn a lot, I’m sure you will too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KbcUahN5ZcbzCjVg.gif" /></figure><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/add-serverless-firebase-push-notifications-react-native-app-chat-app-part-2/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ff1bbc6c479" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/add-serverless-firebase-push-notifications-to-your-react-native-app-chat-app-part-2-8ff1bbc6c479">Add serverless Firebase push notifications to your React Native app — Chat App, part 2</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 chat app with Firebase and Redux, part 1]]></title>
            <link>https://medium.com/react-native-development/build-a-chat-app-with-firebase-and-redux-part-1-8a2197fb0f88?source=rss-690194f3df50------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a2197fb0f88</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Thu, 30 Mar 2017 12:27:09 GMT</pubDate>
            <atom:updated>2017-04-11T18:41:31.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsaRsIEPbaG0gPoM1xEOaQ.png" /></figure><p>Today we’re building a chat app. The first and most important part of a chat app</p><ul><li>users have an identity</li><li>there is a list of messages</li><li>every client gets messages in real-time</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F915vvTQV_tI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D915vvTQV_tI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F915vvTQV_tI%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f620ef8e1f25db67fc5543de98c3c2af/href">https://medium.com/media/f620ef8e1f25db67fc5543de98c3c2af/href</a></iframe><p>The app is a lot like 4chan, Omegle, or Chatroulette — anonymous and global. Pick a name and an avatar, and you’re in. A global chatroom for all to share. Right now the only way in, is to follow this tutorial, build your app, and run it in a simulator. I’ll be there, come say hi</p><p>And that’s why I call this lecture “part 1”.</p><p>A real chat app needs more than that. There should be notifications, updates in the background, optimizations around message fetching … Perhaps a persistent identity and a way to make small chatrooms.</p><p>We’ll add those in the next lecture. <a href="http://eepurl.com/cxTnOL">Subscribe by email</a> to get it in your inbox.</p><p><strong>Here’s what you’ll learn in this lecture:</strong></p><ul><li><strong>how to keep a </strong><strong>ListView scrolled to bottom</strong></li><li><strong>how to use Firebase:</strong></li><li><em>to save data to the cloud</em></li><li><em>as a quick real-time messaging backbone</em></li><li><em>to [anonymously] authenticate users</em></li><li><strong>how to use Redux:</strong></li><li><em>to manage app state</em></li><li><em>using Redux thunks for async state</em></li><li><strong>Shoutem UI toolkit for styling</strong></li><li><strong>how to build a login form</strong></li><li><strong>how to run two simulators side-by-side</strong></li></ul><p>You can see the <a href="https://github.com/shoutem/school/tree/master/ChatApp">full code on Github</a>. To try it out download the repo, cd into ChatApp, run react-native install and react-native run-ios.</p><p>If you’re new to React Native, I suggest starting with the first lecture, <a href="http://school.shoutem.com/lectures/react-native-101-build-first-mobile-app/">React Native 101: Build your first mobile app</a>.</p><p><strong>Today we’re going to </strong>install our dependencies, take a look at how Redux works, set up Firebase, build the basic chat interface with message sending and saving and autoscrolling, add a login form, then run two simulators side-by-side so you can chat with yourself.</p><h3>Install dependencies</h3><p>We use react-native install to install dependencies from npm, link them into our build, and save them to our package.json. For some reason this still isn’t the default in all README files, but I love it.</p><pre>$ react-native init ChatApp<br>$ cd ./ChatApp<br>$ react-native install @shoutem/ui<br>$ react-native install firebase<br>$ react-native install moment<br>$ react-native install redux<br>$ react-native install redux-thunk<br>$ react-native install redux-logger<br>$ react-native install react-native-keyboard-aware-scroll-view</pre><p>We’ll use @shoutem/ui for styling, the firebase SDK so we can talk to Firebase, and moment so we can display pretty timestamps like <em>5 seconds ago</em>. The 3 Redux packages give us redux itself, redux-thunkfor async Redux actions, and redux-logger so our app is easier to debug.</p><p>react-native-keyboard-aware-scroll-view is going to help us keep the UI visible when users open their keyboard. It’s kind of janky, but it’s the simplest solution I’ve found.</p><h3>Redux 101</h3><p>Redux is a state management library that’s popular in the React ecosystem. Many consider Redux to be <em>the</em> state management library so knowing how to use it is a good idea.</p><p>Personally, I’m not a fan. I think it often leads to code architecture that’s hard to understand, distributes business logic between too many files and functions, and requires a lot of typing. Maybe I just haven’t used it enough to get comfortable</p><p>Here are the basics:</p><p>Much like <a href="http://school.shoutem.com/lectures/build-simple-imgur-client-react-native/#mobx-101">MobX</a>, Redux also uses the concept of a global store that contains all of our app state. But with Redux, state is immutable so each time we change something, we create a new copy of our state.</p><p>This happens through reducers. A reducer is a function that takes some state and an action, and creates new state. For example, a reducer for counting would look like this:</p><pre>const counter = (state, action) =&gt; (<br>    switch (action.type) {<br>        case &#39;COUNT_UP&#39;:<br>            return Object.assign({}, state, {<br>                count: state.count + 1<br>            });<br>        default:<br>            return state<br>    }<br>)</pre><p>Yes, just like a function you’d pass to JavaScript’s default .reduce() array method.</p><p>The extra logic comes from how Redux handles actions. An action is an object that tells reducers what to do. Every reducer in your app gets every action that you dispatch.</p><p>That’s why Redux reducers check action.type. It’s a convention a lot of people use to give names to their actions. When a reducer gets called, it checks action.type and performs changes, if necessary.</p><p>Another common convention is to package actions as functions called action generators. Simple verbs that you dispatch in your app that look like this:</p><pre>const countUp = () =&gt; ({<br>    type: &#39;COUNT_UP&#39;<br>})</pre><p>Yes, it looks silly in the countUp example. Real world actions often accept arguments, package additional info as an action payload, and perform <em>some</em> business logic.</p><p>In my experience, this often leads to confusing architectures. Some business logic happens in actions, some happens in reducers. Maybe I just don’t have enough practice 🙂</p><p>If all of this is confusing, don’t worry, I often feel like Redux was designed for people far smarter than me. Building this app helped me figure out how to use it.</p><h3>Set up Firebase</h3><p>Firebase is a real-time cloud database that helps you build apps without building the backend. You can save and retrieve JSON objects, build user authentication, and get data updates in real-time. All we need for a chat app</p><p>Create a new Firebase app on <a href="https://console.firebase.google.com/">your Firebase console</a>. You’ll need a Google Account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*5pO2MnEE_dYPo3Ul.png" /><figcaption>Firebase Console</figcaption></figure><p>Then click on <em>“Add Firebase to your web app”</em>, yes web app, and copy the config keys. This will let you chat with yourself and anyone else who connects to the same database.</p><p>If you use my keys from the <a href="https://github.com/shoutem/school/tree/master/ChatApp">school/ChatApp repository</a>, you can chat with others who follow this tutorial. I’ll keep my simulator running so I can say hi 🙂</p><p>Setup a Firebase singleton in src/firebase.js:</p><pre>import * as firebase from &#39;firebase&#39;;</pre><pre>const config = {<br>    // your config stuff<br>};<br>firebase.initializeApp(config);</pre><pre>export default firebase;</pre><p>This code creates an instance of the Firebase SDK and configures it with your config. Now you can import it anywhere in your codebase and it’s always <em>this</em> singleton.</p><p>When you see firebase from now on, assume that it’s imported from here.</p><p>The last piece of Firebase setup is enabling anonymous access to your database. This lets us avoid building actual authentication and makes our chat app simpler.</p><p>Go to the Authentication tab and make sure Anonymous is enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*12LCCQXYhdYWsA8v.png" /><figcaption>Firebase authentication tab</figcaption></figure><h3>Chat App Redux structure</h3><p>We’re first going to look at all the business logic for our Chat App. I know this feels weird and it’s not how you build apps. Normally this stuff grows alongside building the tangible UI. That’s hard to explain, though.</p><p>If I show you the Redux stuff first, then the UI will be painless. I think. We’ll see 🙂 You can tell me if this approach worked.</p><p>Our Chat App needs to store a user, a list of messages, and some meta info for the UI. This is the data shape we’re aiming for:</p><pre>{<br>    chatroom: {<br>        messages: [<br>            {<br>                id: string,<br>                text: string,<br>                time: timestamp,<br>                author: {<br>                    name: string,<br>                    avatar: string<br>                }<br>            },<br>            ...<br>        ],<br>        meta: {<br>            isFetching: boolean,<br>            lastFetched: timestamp,<br>            height: integer<br>        }<br>    },<br>    user: {<br>        name: string,<br>        avatar: string,<br>        authorized: boolean,<br>        authorizing: boolean<br>    }<br>}</pre><p>The chatroom contains a list of messages. Each message has an id, some text, the time it was sent at, and an author. Each author is just the user info from every client.</p><p>Yes, that leads to a lot of duplicate data, but it’s easier to build. Instead of worrying about user lists and saving relational info, we package every author together with their message. Simpler to store, simpler to display.</p><p>The chatroom also contains some meta info. isFetching tells us when to show a loading spinner, height tells us how much scrolling to do, and lastFetched seemed like a good idea at the time, but turned out to be pointless. We might use it to periodically check for messages in <a href="http://eepurl.com/cxTnOL">part 2 of this lecture</a>.</p><p>And the user is a combination of name and avatar. Collected by the login form that we’ll add last.</p><p>Here’s what that looks like as a bunch of reducers</p><p>You can see the <a href="https://github.com/shoutem/school/tree/master/ChatApp/src/reducers">full reducer code on Github</a>.</p><h3>root reducer</h3><pre>// src/reducers/index.js<br>const rootReducer = combineReducers({<br>    chatroom,<br>    user<br>});</pre><p>Our rootReducer is built as a combination of the chatroom and user reducers. That makes them top level keys in our data store, which now looks like this:</p><pre>{<br>    chatroom: {},<br>    user: {}<br>}</pre><p>I don’t know <em>exactly</em> how combineReducer works, but I think it’s essentially a reducer that calls other reducers on object keys. Something like having a function that returns {chatroom: chatroom(state, action), user: user(state, action)}.</p><p>combineReducers is easier to type</p><h3>chatroom reducer</h3><pre>// src/reducers/chatroom.js<br>const meta = (state = initialState, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;START_FETCHING_MESSAGES&#39;:<br>            return Object.assign({}, state, {<br>                isFetching: true<br>            });<br>        case &#39;RECEIVED_MESSAGES&#39;:<br>            return Object.assign({}, state, {<br>                isFetching: false,<br>                lastFetched: action.receivedAt<br>            });<br>        case &#39;UPDATE_MESSAGES_HEIGHT&#39;:<br>            return Object.assign({}, state, {<br>                height: action.height<br>            });<br>        default:<br>            return state<br>    }<br>}</pre><pre>const chatroom = combineReducers({<br>    messages,<br>    meta<br>});</pre><p>The chatroom reducer is built from two reducers. A chatroom reducer that acts much like the root reducer. It combines messages and meta reducers.</p><p>The meta reducer builds our chatroom’s metadata. Yes, it’s a lot of code, but look closely. All it does, is to copy action key values into state key values.</p><p>I’m sure a more advanced Reduxer than myself knows many ways to avoid typing all this.</p><h3>messages reducer</h3><p>The messages reducer is built from two reducers. One for creating single messages, another for building lists of messages.</p><pre>// src/reducers/messages.js<br>const message = (state, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;ADD_MESSAGE&#39;:<br>            return {<br>                id: action.id,<br>                text: action.text,<br>                time: action.time,<br>                author: action.author<br>            }<br>        case &#39;SEND_MESSAGE&#39;:<br>            let msg = {<br>                text: action.text,<br>                time: Date.now(),<br>                author: {<br>                    name: action.user.name,<br>                    avatar: action.user.avatar<br>                }<br>            };</pre><pre>            const newMsgRef = firebase.database()<br>                                      .ref(&#39;messages&#39;)<br>                                      .push();<br>            msg.id = newMsgRef.key;<br>            newMsgRef.set(msg);</pre><pre>            return msg;<br>        default:<br>            return state<br>    }<br>}</pre><p>Just like the meta reducer, most of message‘s code just copies values from action keys to state keys. When action.type is SEND_MESSAGE it also saves the message to firebase.</p><p>Saving happens through Firebase’s push() feature. It adds an object to the end of a list and returns its id.</p><p>The difference between SEND_MESSAGE and ADD_MESSAGE is that the first also saves it to Firebase and the second doesn’t. This is important because we want to use ADD_MESSAGE when fetching messages back from Firebase.</p><p>I don’t know if a reducer is the best place to put this logic, or if sending to Firebase should happen in the action. You could make an argument for either.</p><pre>// src/reducers/messages.js<br>const messages = (state = [], action) =&gt; {<br>    switch (action.type) {<br>        case &#39;ADD_MESSAGE&#39;:<br>            if (state.map(m =&gt; m.id).includes(action.id)) {<br>                return state;<br>            }else{<br>                return [<br>                ...state,<br>                message(undefined, action)<br>                ]<br>            }<br>        case &#39;SEND_MESSAGE&#39;:<br>            return [<br>                ...state,<br>                message(undefined, action)<br>            ]<br>        default:<br>            return state<br>    }<br>};</pre><p>The messages reducer uses message to build a new message and adds it to the array. When adding, it also makes sure that messages aren’t duplicated by checking message ids.</p><h3>user reducer</h3><pre>// src/reducers/user.js<br>const user = (state = initialState, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;SET_USER_NAME&#39;:<br>            return Object.assign({}, state, {<br>                name: action.name<br>            });<br>        case &#39;SET_USER_AVATAR&#39;:<br>            return Object.assign({}, state, {<br>                avatar: action.avatar<br>            });<br>        case &#39;USER_START_AUTHORIZING&#39;:<br>            return Object.assign({}, state, {<br>                authorizing: true<br>            });<br>        case &#39;USER_AUTHORIZED&#39;:<br>            return Object.assign({}, state, {<br>                authorizing: false,<br>                authorized: true<br>            });</pre><pre>        default:<br>            return state<br>    }<br>}</pre><p>user is another simple reducer. It takes key values from the action and puts them into state. No logic here.</p><p>We’re going to use authorizing to change the login button into a spinner, and authorized to show the chat UI.</p><h3>Chat App Redux actions</h3><p>You can see which actions we need in the list of reducers. Here they are again:</p><ul><li>ADD_MESSAGE, adds a message to the list</li><li>SEND_MESSAGE, sends a message to Firebase and adds it to the list</li><li>START_FETCHING_MESSAGES, sets the isFetching flag</li><li>RECEIVED_MESSAGES, unsets the flag</li><li>UPDATE_MESSAGES_HEIGHT, updates chatroom.meta.height when we add messages</li><li>SET_USER_NAME, sets user.name</li><li>SET_USER_AVATAR, sets user.avatar</li><li>USER_START_AUTHORIZING, sets authorizing flag</li><li>USER_AUTHORIZED, unsets authorizing flag and sets authorized flag</li></ul><p>All of these actions are similar and look something like this:</p><pre>// src/actions/index.js<br>export const setUserName = (name) =&gt; ({<br>    type: &#39;SET_USER_NAME&#39;,<br>    name<br>});</pre><p>If you were mean, you could call them boilerplate.</p><h3>The interesting actions — thunks?</h3><p>We also have some interesting actions. I think they’re called thunks in the Redux world. Or maybe they’re thunks only if they trigger other actions and/or return functions instead of objects. Either way, these feel a lot more powerful and less boilerplatey.</p><p>We have two thunks: fetchMessages for fetching messages and subscribing to Firebase updates, and login to authenticate a user.</p><h4>FETCHMESSAGES</h4><pre>// src/actions/index.js<br>export const fetchMessages = () =&gt; {<br>    return function (dispatch) {<br>        dispatch(startFetchingMessages());</pre><pre>        firebase.database()<br>                .ref(&#39;messages&#39;)<br>                .on(&#39;value&#39;, (snapshot) =&gt; {<br>                    // gets around Redux panicking about actions in reducers<br>                    setTimeout(() =&gt; {<br>                        const messages = snapshot.val() || [];</pre><pre>                        dispatch(receiveMessages(messages))<br>                    }, 0);<br>                });<br>    }<br>}</pre><pre>export const receiveMessages = (messages) =&gt; {<br>    return function (dispatch) {<br>        Object.values(messages).forEach(msg =&gt; dispatch(addMessage(msg)));</pre><pre>        dispatch(receivedMessages());<br>    }<br>}</pre><p>Here’s how fetchMessages works:<br>1. dispatch START_FETCHING_MESSAGES, which sets the isFetching flag<br>2. Subscribe to value changes on messages list in Firebase<br>3. On every update, dispatch receiveMessages with a list of messages. A timeout avoids Redux thinking that reducers are triggering actions. This is a smell and I’m doing something wrong.<br>4. receiveMessages triggers an ADD_MESSAGE action for each message<br>5. Trigger RECEIVED_MESSAGES to unset isFetching flag</p><p>Here is a helpful diagram. This is the core of our chat app so you should understand how it works. 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ve69BRe2pAzPjLw-.jpg" /></figure><h4><strong>LOGIN</strong></h4><p>The login thunk is simpler in comparison. It authorizes our user and initiates the first message fetch.</p><pre>// src/actions/index.js<br>export const login = () =&gt; {<br>    return function (dispatch) {<br>        dispatch(startAuthorizing());</pre><pre>        firebase.auth()<br>                .signInAnonymously()<br>                .then(() =&gt; {<br>                    dispatch(userAuthorized());<br>                    dispatch(fetchMessages());<br>                });<br>    }<br>}</pre><p>When we call login, it uses startAuthorizing to set the authorizing flag, then uses Firebase’s signInAnonymously feature. When that’s done, it marks the user as authorized and initiates message fetching.</p><p>This pile of actions and thunks is a common pattern in async redux. You first announce that you’re doing something, then you do it, then you announce that you’re done. This way the interface can show spinners and such. You’ll see.</p><p>That concludes all our business logic. If you’re confused, I suggest looking at <a href="https://github.com/shoutem/school/tree/master/ChatApp/src/reducers">all the reducers</a> and <a href="https://github.com/shoutem/school/tree/master/ChatApp/src/actions">the actions file</a> on Github. Combining those two creates all the business logic for our app.</p><p>But if you’re like me, it’s only going to make sense once you build the UI.</p><h3>The App component</h3><p>Now that we have our business logic, the main work is in piecing together React components to build the UI and triggering Redux actions when appropriate. Most of our components are going to have <em>some</em>knowledge of state, so in true Redux parlance they are called containers. Some are purely presentational, so they’re called “components”.</p><p>The distinction between containers and presentational components isn’t super useful in our small app. We’ll try to follow conventions anyway.</p><p>Our App component renders a Provider and a simple container.</p><pre>// src/App.js<br>const LoginOrChat = connect(<br>    (state) =&gt; ({<br>        authorized: state.user.authorized<br>    })<br>)(({ authorized }) =&gt; {<br>    if (authorized) {<br>        return (&lt;ChatUI /&gt;);<br>    }else{<br>        return (&lt;LoginUI /&gt;);<br>    }<br>});</pre><pre>class App extends Component {<br>    render() {<br>        return (<br>            &lt;Provider store={store}&gt;<br>               &lt;LoginOrChat /&gt;<br>            &lt;/Provider&gt;<br>        );<br>    }<br>}</pre><p>A Redux Provider puts our data store in a <a href="https://facebook.github.io/react/docs/context.html">React context</a>. This makes it easy to share between components.</p><p>To make a container, in this case LoginOrChat, we use connect(). You can think of it as a higher order component that takes a mapStateToProps function and a React component. It uses mapStateToPropsto pick keys from state and put them in React props when rendering the given component.</p><p>LoginOrChat checks our user.authorized flag and decides what to render: the ChatUI, or the LoginUI. You saw the action that flips this flag earlier. It’s called login.</p><p>While we’re setting things up in App.js, we also create the data store and add some middleware. The thunk middleware enables our async workflow and lets us trigger actions from actions, and the loggermiddleware is great for debugging our app.</p><pre>const loggerMiddleware = createLogger();</pre><pre>const store = createStore(<br>    rootReducer,<br>    applyMiddleware(<br>        thunkMiddleware,<br>        loggerMiddleware<br>    )<br>);</pre><p>Logger creates console output like this on every Redux action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*Li6R_RnBiD41qu-R.png" /><figcaption>loggerMiddleware</figcaption></figure><p>You can see the <a href="https://github.com/shoutem/school/blob/master/ChatApp/src/App.js">full App.js code on Github</a>.</p><h3>ChatUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*gosIkmPAMhRfDpPM.png" /><figcaption>Chat app interface</figcaption></figure><p>Our chat interface is built from 3 components:<br>– a header<br>– a list of messages<br>– a text input</p><p>We use <a href="https://github.com/APSL/react-native-keyboard-aware-scroll-view">KeyboardAwareScrollView</a> to make room for the onscreen keyboard. You’d think iOS and Android handle that on their own wouldn’t you? Nope.</p><pre>// src/components/ChatUI.js<br>class ChatUI extends Component {<br>render() {<br>// ...<br>        return (<br>            &lt;Screen&gt;<br>                &lt;Title styleName=&quot;h-center&quot; style={{paddingTop: 20}}&gt;<br>                    Global Chatroom<br>                &lt;/Title&gt;<br>                &lt;KeyboardAwareScrollView ref=&quot;scroll&quot;<br>                                         onLayout={this.onScrollViewLayout}&gt;<br>                    &lt;Messages /&gt;<br>                    &lt;Input onLayout={this.onInputLayout}<br>                           onFocus={this._scrollToInput.bind(this)}<br>                           submitAction={this.sendMessage}<br>                           ref=&quot;input&quot;<br>                           placeholder=&quot;Say something cool ...&quot; /&gt;<br>                &lt;/KeyboardAwareScrollView&gt;<br>            &lt;/Screen&gt;<br>        )<br>    }<br>}</pre><p>Screen and Title come from Shoutem UI Toolkit, they’re styled components. Input is a reusable input component that I’ll show you in the next section, and KeyboardAwareScrollView is the scroll view that automagically makes room for the keyboard.</p><p>So what’s with all the onLayout stuff? That’s for autoscrolling the scroll view to the bottom.</p><h3>Autoscroll ChatUI to the bottom</h3><p>You see stuff like that doesn’t happen on its own in native apps. You have to add the logic yourself.</p><p>Remember that UPDATE_MESSAGES_HEIGHT action? That’s used here. We use onLayout internally in Messages to detect component size changes and trigger the action. That tells everyone else.</p><p>Then ChatUI detects that as a componentWillUpdate because its props depend on it, calculates how much it should scroll down, and scrolls.</p><p>The full logic in ChatUI uses some local state and looks like this:</p><pre>// src/components/ChatUI<br>class ChatUI extends Component {<br>    state = {<br>        scrollViewHeight: 0,<br>        inputHeight: 0<br>    }</pre><pre>    componentDidMount() {<br>        this.scrollToBottom(false);<br>    }</pre><pre>    componentDidUpdate() {<br>        this.scrollToBottom();<br>    }</pre><pre>    onScrollViewLayout = (event) =&gt; {<br>        const layout = event.nativeEvent.layout;</pre><pre>        this.setState({<br>            scrollViewHeight: layout.height<br>        });<br>    }</pre><pre>    onInputLayout = (event) =&gt; {<br>        const layout = event.nativeEvent.layout;</pre><pre>        this.setState({<br>            inputHeight: layout.height<br>        });<br>    }</pre><pre>    scrollToBottom(animate = true) {<br>        const { scrollViewHeight, inputHeight } = this.state,<br>              { chatHeight } = this.props;</pre><pre>        const scrollTo = chatHeight - scrollViewHeight + inputHeight;</pre><pre>        if (scrollTo &gt; 0) {<br>           this.refs.scroll.scrollToPosition(0, scrollTo, animate)<br>        }<br>    }</pre><pre>    _scrollToInput(reactRef) {<br>        this.refs.scroll.scrollToFocusedInput(ReactNative.findNodeHandle(reactRef));<br>    }<br></pre><pre>    sendMessage = (text) =&gt; {<br>        return sendMessage(text, this.props.user)<br>    }<br>    <br>        // ...<br>}</pre><p>That looks like a lot of code and it is, but it’s repetitive. The key part is this scrollToBottom method:</p><pre>scrollToBottom(animate = true) {<br>    const { scrollViewHeight, inputHeight } = this.state,<br>          { chatHeight } = this.props;</pre><pre>    const scrollTo = chatHeight - scrollViewHeight + inputHeight;</pre><pre>    if (scrollTo &gt; 0) {<br>        this.refs.scroll.scrollToPosition(0, scrollTo, animate)<br>    }<br>}</pre><p>It takes the rendered height of our KeyboardAwareScrollView and the rendered height of our Inputand the known height of all chat messages, calculates how much to scroll, and scrolls. The idea is that we scroll down as far as all the messages, but leave enough room for a screen’s worth of messages and the input box to remain visible.</p><p>Kinda weird, I know, but that’s the kind of stuff you gotta do in native apps. No browser HTML and CSS to do it for you</p><p>You can see the <a href="https://github.com/shoutem/school/blob/master/ChatApp/src/components/ChatUI.js">full ChatUI code on Github</a></p><h3>Messages component</h3><p>The Messages component isn’t very interesting. We’ve talked about <a href="http://school.shoutem.com/lectures/build-simple-imgur-client-react-native/">ListViews before</a>. We use a <a href="http://shoutem.github.io/docs/ui-toolkit/components/list-view">Shoutem UI Toolkit Listview</a>, feed it our list of messages and let it handle itself.</p><p>I took the layout and styling for each message from a <a href="http://shoutem.github.io/docs/ui-toolkit/components/rows">Shoutem Rows example</a>. Seemed to look nice enough.</p><p>You <em>can</em> implement this part from scratch, I did. That’s why I’d suggest you do some copypasta from Github. You’ll need these two files:</p><ul><li><a href="https://github.com/shoutem/school/blob/master/ChatApp/src/containers/Messages.js">containers/Messages</a> decides between a spinner and the `MessageList</li><li><a href="https://github.com/shoutem/school/blob/master/ChatApp/src/components/MessageList.js">components/MessageList</a> renders a ListView with messages.</li></ul><h3>The reusable Input component</h3><p>This is a fun component. I’m quite happy with it. We use it for all inputs in our app. The message input, the username, and the avatar. Three functions, one component.</p><p>How? It accepts a Redux action as one of its props.</p><pre>// src/containers/Input.js<br>class Input extends Component {<br>    state = {<br>        text: null<br>    }</pre><pre>    onChangeText = text =&gt; this.setState({text: text});</pre><pre>    onSubmitEditing = () =&gt; {<br>        this.props.dispatch(<br>            this.props.submitAction(this.state.text)<br>        );</pre><pre>        if (!this.props.noclear) {<br>            this.setState({<br>                text: null<br>            });<br>        }<br>    }</pre><pre>    onFocus = (event) =&gt; {<br>        if (this.props.onFocus) {<br>            this.props.onFocus(this.refs.input);<br>        }<br>    }</pre><pre>    onBlur = () =&gt; {<br>        if (this.props.submitOnBlur) {<br>            this.onSubmitEditing();<br>        }<br>    }</pre><pre>    onLayout = (event) =&gt; {<br>        if (this.props.onLayout) {<br>            this.props.onLayout(event);<br>        }<br>    }</pre><pre>    render() {<br>        return (<br>            &lt;TextInput placeholder={this.props.placeholder}<br>                       onChangeText={this.onChangeText}<br>                       onSubmitEditing={this.onSubmitEditing}<br>                       onLayout={this.onLayout}<br>                       value={this.state.text}<br>                       onFocus={this.onFocus}<br>                       onBlur={this.onBlur}<br>                       ref=&quot;input&quot;/&gt;<br>        )<br>    }<br>}</pre><p>Our Input component renders as a Shoutem TextInput. It gets a placeholder, the current value, and a bunch of event callbacks.</p><p>We use local state to store currently typed text until we’re ready to dispatch an action in onSubmitEditing. This submit triggers when we press &lt;enter&gt; in the Simulator, or click Return on the keyboard.</p><p>When this happens, we clear the text unless the noclear flag is set. This allows us to clear the current message in ChatUI and keep username/avatar in LoginUI.</p><p>We also submit on blur because I thought that made the interface more intuitive. At least in the login form.</p><p>You can see the <a href="https://github.com/shoutem/school/blob/master/ChatApp/src/containers/Input.js">full Input code on Github</a></p><p>If you’ve been following along, and you set authorized to true by default, you should now see a chat interface in your simulator. Sending a message might cause an error because your state.user isn’t set up yet, but you can see everyone else’s messages. Exciting!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*yYqLuxQw2a_t1E6L.png" /><figcaption>Chat app interface</figcaption></figure><h3>LoginUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*4PP3b08Tru1Ul6hB.png" /><figcaption>Login form</figcaption></figure><p>We already have the Input components and all the business logic for our user authentication. All that’s left to do is to put them together.</p><pre>// src/components/LoginUI.js<br>class LoginUI extends Component {<br>    render() {<br>        return (<br>            &lt;Screen style={{alignItems: &#39;center&#39;, justifyContent: &#39;center&#39;}}&gt;<br>                &lt;Title&gt;Who are you?&lt;/Title&gt;<br>                &lt;Divider /&gt;</pre><pre>                &lt;Input placeholder=&quot;Your name here&quot;<br>                       submitAction={setUserName}<br>                       submitOnBlur<br>                       noclear<br>                       ref=&quot;username&quot;/&gt;<br>                &lt;Divider /&gt;</pre><pre>                &lt;Input placeholder=&quot;Your avatar URL here&quot;<br>                       submitAction={setUserAvatar}<br>                       submitOnBlur<br>                       noclear<br>                       ref=&quot;avatar&quot;/&gt;<br>                &lt;Divider /&gt;</pre><pre>                {this.props.authorizing ? &lt;Spinner /&gt; : &lt;LoginButton /&gt;}<br>            &lt;/Screen&gt;<br>        );<br>    }<br>}</pre><p>We render a Title with some text, two Inputs and either a Spinner or a LoginButton. Yes, this is technically a smart component too, it needs to know about user.authorizing.</p><p>Notice that both Input components are virtually the same, they just fire different Redux actions.</p><p>You can see the <a href="https://github.com/shoutem/school/blob/master/ChatApp/src/components/LoginUI.js">full LoginUI code on Github</a></p><p>Similarly, LoginButton is just a button with some text that triggers the login() action when pressed. You can see its <a href="https://github.com/shoutem/school/blob/master/ChatApp/src/containers/LoginButton.js">code on Github</a>.</p><p>Congratz! You should now have a working chat app that lets you talk with yourself. Or with everyone who’s built this app, if you used my Firebase config.</p><h3>Run two simulators side-by-side</h3><p>The last step is to run two simulators. That lets you run two apps side-by-side, which makes debugging a lot more fun.</p><p>Follow these steps:</p><ol><li>$ cd /Applications/Xcode.app/Contents/Developer/Applications</li><li>$ open -n Simulator.app</li><li>Wait for error about starting Simulator in this config. Press OK.</li><li>Choose the simulator without a window, pick a different Hardware config</li><li>$ cd ~/Your/ChatApp/Path</li><li>react-native run-ios --simulator &quot;iPhone 6s&quot; or whichever hardware you picked in 4</li><li>2 simulators</li></ol><p>You can now talk to yourself 🙂</p><p><a href="https://medium.com/react-native-development/add-serverless-firebase-push-notifications-to-your-react-native-app-chat-app-part-2-8ff1bbc6c479">Add serverless Firebase push notifications to your React Native app — Chat App, part 2</a></p><p><a href="http://eepurl.com/cxTnOL">Subscribe by email</a> to get the next lecture where we add notifications, background app sync, and maybe even separate chatrooms.</p><p>What do you wanna build next? <a href="/service/mailto:hi@swizec.com?subject=Build+this+app">Email me</a>, I read everything.</p><p><em>Originally published at </em><a href="https://school.shoutem.com/lectures/chat-app-firebase-redux-react-native/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a2197fb0f88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/build-a-chat-app-with-firebase-and-redux-part-1-8a2197fb0f88">Build a chat app with Firebase and Redux, part 1</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 lunch recommendation app — React Native School]]></title>
            <link>https://medium.com/react-native-development/build-a-lunch-recommendation-app-react-native-school-fdc05de70811?source=rss-690194f3df50------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc05de70811</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 11:01:38 GMT</pubDate>
            <atom:updated>2017-03-20T12:28:24.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9Ybjl1OL8nApNQF_I8PVw.png" /></figure><p>You know those moments when you want to grab some lunch, a coffee, or drinks with friends, but nothing you can think of feels right? It’s gonna take an hour before you make moves and you’re hungry.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FynxgST6NWR4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DynxgST6NWR4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FynxgST6NWR4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/35fa0fcf76e9cf636c579d1952f6edd0/href">https://medium.com/media/35fa0fcf76e9cf636c579d1952f6edd0/href</a></iframe><p>We can build an app for that. A lunch spot app that opens as a full screen map, asks what you feel like doing, and suggests 10 places within walking distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*X-QWm99ZBIhvJ5evxXG4_w.gif" /></figure><p>You might still bicker with your friends, but you’ll with objective data! There’s no way you’re getting dragged to that bar with soggy toast. Not today, friends, not today.</p><p>Wanna build a new app with me every 2 weeks? <a href="http://eepurl.com/cxTnOL">Subscribe by email</a> and you’ll never miss a lesson.</p><h3>Here’s what you’ll learn today:</h3><ul><li>how to use geolocation in React Native</li><li>how to use <a href="https://github.com/airbnb/react-native-maps">AirBnB’s react-native-maps</a> library</li><li>how to speed up styling with <a href="https://shoutem.github.io/ui/">Shoutem’s UI toolkit</a></li></ul><p>We’re going to avoid state management libraries because I don’t think we need them. There’s <em>some</em> state we’ll have to manage, like the user’s current location and a list of restaurants, but we can do that in App.state.</p><p>That means <em>all</em> state lives in the main component’s state and is passed down through props. Callbacks go back up the chain and change state when necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-t8k3bm0wjwi3JZl.jpg" /><figcaption>Architecture sketch</figcaption></figure><p>If you’re new to React Native, I suggest starting with <a href="http://school.shoutem.com/lectures/react-native-101-build-first-mobile-app/">React Native 101</a> where you build your first app.</p><p>You can see the full code for <a href="https://github.com/shoutem/school/tree/master/LunchSpotApp">LunchSpotApp on Github</a>.</p><h3>Install dependencies</h3><p>We need Shoutem’s UI Toolkit, AirBnB’s map library, and <a href="https://github.com/sindresorhus/query-string">query-string</a>, which will make it easier to build Foursquare requests. Yes, we’re using Foursquare and no it’s not dead. I like it.</p><pre>$ react-native install @shoutem/ui<br>$ react-native install react-native-vector-icons<br>$ react-native install react-native-linear-gradient<br>$ react-native install react-native-maps@0.13.0<br>$ react-native install query-string</pre><p>I like to use react-native install to install dependencies because it installs libraries from npm, links them into the project, and saves them to package.json. Many tutorials still suggest npm install and linking manually. This is easier.</p><p>We need react-native-vector-icons and react-native-linear-gradient to work around a <a href="https://github.com/shoutem/ui/issues/149">Shoutem UI Toolkit bug</a> with missing fonts. I don’t know <em>how</em> this fixes the bug, but it does. Fingers crossed the team releases a fixed version soon.</p><p>Similarly, we have to install a specific version of react-native-maps. As of March 6th, 2017 0.13.0 is the latest version, but npm thinks 0.12.4 is the latest. That one breaks with the latest React Native.</p><p>Welcome to the bleeding edge. Run react-native init every few weeks and you’ll have some fun problems to deal with.</p><p>That must be why people don’t start new apps so often.</p><h3>Run the app, update index.ios.js</h3><p>You should now see the default app, if you run react-native run-ios. Go into index.ios.js and remove all of that. Replace run-ios with run-android and index.ios with index.android, if you prefer the Android simulator.</p><p>Your index file should look like this:</p><pre>import React, { Component } from &#39;react&#39;;<br>import {<br>  AppRegistry,<br>} from &#39;react-native&#39;;<br><br>import App from &#39;./components/App&#39;;<br><br>export default class LunchSpotApp extends Component {<br>    render() {<br>        return (&lt;App /&gt;);<br>    }<br>}<br><br>AppRegistry.registerComponent(&#39;LunchSpotApp&#39;, () =&gt; LunchSpotApp);</pre><p>iOS and Android can share the App component we’re building.</p><h3>File structure</h3><p>Through this tutorial, we’re going to build 4 files:</p><pre>LunchSpotApp<br>  └─ components<br>      └─ App.js<br>      └─ Recommendation.js<br>      └─ RecommendationsMap.js<br>      └─ Topics.js<br>      └─ styles.js<br>  └─ index.ios.js<br>  └─ index.android.js</pre><p>Actually, you should just grab <a href="https://github.com/shoutem/school/blob/master/LunchSpotApp/components/styles.js">styles.js from Github</a>. Explaining it would just clutter up the code samples.</p><h3>Render a map with user’s geolocation</h3><p>React Native comes with a polyfill for <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/geolocation">HTML5’s navigator</a>.geolocation API. You can get the current location and watch it for updates. Super useful when the user is moving.</p><p>The easiest place to do that is in App.componentWillMount. We start observing geolocation when App first renders, and stop when it unmounts.</p><pre>./components/App.js<br><br>class App extends Component {<br>    state = {<br>        mapRegion: null,<br>        gpsAccuracy: null<br>    }<br>    watchID = null<br><br>    componentWillMount() {<br>        this.watchID = navigator.geolocation.watchPosition((position) =&gt; {<br>            let region = {<br>                latitude: position.coords.latitude,<br>                longitude: position.coords.longitude,<br>                latitudeDelta: 0.00922*1.5,<br>                longitudeDelta: 0.00421*1.5<br>            }<br><br>            this.onRegionChange(region, position.coords.accuracy);<br>        });<br>    }<br><br>    componentWillUnmount() {<br>        navigator.geolocation.clearWatch(this.watchID);<br>    }<br><br>    onRegionChange(region, gpsAccuracy) {<br>        this.fetchVenues(region);<br><br>        this.setState({<br>            mapRegion: region,<br>            gpsAccuracy: gpsAccuracy || this.state.gpsAccuracy<br>        });<br>    }<br>}</pre><p>That’s a lot of code to spring on you all at once. Let me explain.</p><p>We set up default state: an empty mapRegion and gpsAccuracy. It’s called region because that’s what react-native-maps uses. Consistency makes code easier to read.</p><p>We start a geolocation watch in componentWillMount with navigation.geolocation.watchPosition. I don’t know what happens behind the scenes, but the environments triggers our callback every time new information becomes available. In the form of a position object with many properties.</p><p>The properties we care about are latitude, longitude, and accuracy. We use latitude and longitude to center the map and run the Foursquare query, and we use accuracy to give the user a familiar visual. Bigger or smaller circle based on GPS accuracy.</p><p>In componentWillUnmount we clean up after ourselves and stop listening to location changes.</p><p>onRegionChange doubles as a MapView callback when the user zooms and pans. We want the same effect for both physically moving and for changing the view. It makes sense to combine them into one callback.</p><p>Whenever the region changes, we save it to state, which triggers a re-render, and fetch a new set of Foursquare recommendations. You’ll see how that works in the next section.</p><h3>Render the map</h3><p>Now that we know where we are, we can render the map. That happens in App.render and the RecommendationsMap component.</p><pre>./components/App.js<br><br>class App extends Component {<br>        // ...<br>    render() {<br>        const { mapRegion, lookingFor } = this.state;<br><br>        if (mapRegion) {<br>            return (<br>                &lt;Screen&gt;<br>                    &lt;RecommendationsMap {...this.state} onRegionChange={this.onRegionChange.bind(this)} /&gt;<br>                &lt;/Screen&gt;<br>            );<br>        }else{<br>            return (<br>                &lt;Screen style={styles.centered}&gt;<br>                    &lt;Spinner styleName=&quot;large&quot; /&gt;<br>                &lt;/Screen&gt;<br>            );<br>        }<br>    }<br>}</pre><p>Here’s how App.render works: If we have a location, we render the map, otherwise we render a Spinner.</p><p>Screen and Spinner are Shoutem UI Toolkit components. Screen is a lot like the default View, except it has a nice background that matches your overall theme. Themes are configurable, but I think the default looks great. Spinner is a spinner image. The kind you’ve seen many times 🙂</p><p>If we do know where we are — mapRegion is defined – then we render RecommendationsMap. We pass all of this.state as props and give it an onRegionChange callback. The map component is going to call this function every time the user drags our map.</p><h3>RecommendationsMap component</h3><p>We let react-native-maps deal with rendering the map.</p><pre>// ./components/RecommendationsMap.js<br><br>import MapView from &#39;react-native-maps&#39;;<br><br>const RecommendationsMap = ({ mapRegion, gpsAccuracy, recommendations, lookingFor,<br>                              headerLocation, onRegionChange }) =&gt; (<br><br>    &lt;MapView.Animated region={mapRegion}<br>                      style={styles.fullscreen}<br>                      onRegionChange={onRegionChange}&gt;<br><br>        &lt;Title styleName=&quot;h-center multiline&quot; style={styles.mapHeader}&gt;<br>            {lookingFor ? `${lookingFor} in` : &#39;&#39;} {headerLocation}<br>        &lt;/Title&gt;<br><br>        &lt;MapView.Circle center={mapRegion}<br>                        radius={gpsAccuracy*1.5}<br>                        strokeWidth={0.5}<br>                        strokeColor=&quot;rgba(66, 180, 230, 1)&quot;<br>                        fillColor=&quot;rgba(66, 180, 230, 0.2)&quot;<br>                        /&gt;<br><br>        &lt;MapView.Circle center={mapRegion}<br>                        radius={5}<br>                        strokeWidth={0.5}<br>                        strokeColor=&quot;rgba(66, 180, 230, 1)&quot;<br>                        fillColor=&quot;rgba(66, 180, 230, 1)&quot;<br>                        /&gt;<br>    &lt;/MapView.Animated&gt;<br>);<br><br>export default RecommendationsMap;</pre><p>You can see <a href="https://github.com/shoutem/school/blob/master/LunchSpotApp/components/RecommendationsMap.js">this file on Github</a>.</p><p>We use MapView to render the map. The .Animated version makes region changes smoother. Playing around, I needed this to make the app work, but I don’t know <em>why</em>. Couldn’t figure it out for the life of me</p><p>My understanding is that the only time you <em>wouldn’t</em> use .Animated is if you’re certain that you don’t need to detect or programmatically cause region changes. That is not the case for us.</p><p>Title is another component from the Shoutem Toolkit. It styles typography so text looks great as a title. I’ll explain the lookingFor and headerLocation props later. You can set this as a Hello Humans text for now, but don’t forget to change later.</p><p>Two MapView.Circles render a location indicator. The small circle is a faux dot, the big circle indicates accuracy. The bigger the circle, the less accurate we your location. Just like in Google Maps.</p><p>Your app should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*tiJ217aC20kr4vJ4.png" /><figcaption>LunchSpotApp with a blank map</figcaption></figure><p>Yes it does use Google Maps by default on Android and Apple Maps on iOS. You can change that, too.</p><h3>Load Foursquare recommendations</h3><p>Time to fill our map with recommendations. I like Foursquare more than Yelp, so we’re using that. If you know something even better, <a href="https://twitter.com/Swizec">yell at me on twitter</a>.</p><p>The bulk of our logic happens in App. If you want to use MobX, this goes in a Store, if you like Redux, it goes in a reducer of some sort. I think.</p><p>Anyway … you’ll need a Foursquare CLIENT_ID and CLIENT_SECRET. You can get them from <a href="https://developer.foursquare.com/">Foursquare’s developer portal</a>.</p><pre>./components/App.js<br><br>const CLIENT_ID = &#39;your_id&#39;;<br>const CLIENT_SECRET = &#39;your_secret&#39;;<br>const FOURSQUARE_ENDPOINT = &#39;https://api.foursquare.com/v2/venues/explore&#39;;<br>const API_DEBOUNCE_TIME = 2000;<br><br>class App extends Component {<br>    state = {<br>        // ...<br>        recommendations: [],<br>        lookingFor: null,<br>        headerLocation: null,<br>        last4sqCall: null<br>    }<br>    <br>    // ...<br>    <br>    fetchVenues(region, lookingFor) {<br>        if (!this.shouldFetchVenues(lookingFor)) return;<br><br>        const query = this.venuesQuery(region, lookingFor);<br><br>        fetch(`${FOURSQUARE_ENDPOINT}?${query}`)<br>            .then(fetch.throwErrors)<br>            .then(res =&gt; res.json())<br>            .then(json =&gt; {<br>                if (json.response.groups) {<br>                    this.setState({<br>                        recommendations: json.response.groups.reduce(<br>                            (all, g) =&gt; all.concat(g ? g.items : []), []<br>                        ),<br>                        headerLocation: json.response.headerLocation,<br>                        last4sqCall: new Date()<br>                    });<br>                }<br>            })<br>            .catch(err =&gt; console.log(err));<br>    }<br><br>    shouldFetchVenues(lookingFor) {<br>        return lookingFor != this.state.lookingFor<br>             || this.state.last4sqCall === null<br>             || new Date() - this.state.last4sqCall &gt; API_DEBOUNCE_TIME;<br>    }<br><br>    venuesQuery({ latitude, longitude }, lookingFor) {<br>        return queryString({<br>            client_id: CLIENT_ID,<br>            client_secret: CLIENT_SECRET,<br>            v: 20170305,<br>            ll: `${latitude}, ${longitude}`,<br>            llAcc: this.state.gpsAccuracy,<br>            section: lookingFor || this.state.lookingFor || &#39;food&#39;,<br>            limit: 10,<br>            openNow: 1,<br>            venuePhotos: 1<br>        });<br>    }<br>}</pre><p>Oh my that was a lot of code again.</p><p>Here’s how it works: fetchVenues is the brains of the operation. It uses fetch() to talk to Foursquare, and updates this.state when new recommendations fly in.</p><p>Because recommendations come in nested groups, we flatten them with json.response.groups.reduce. You can think of it as walking through an array of arrays and concatenating them into one big array.</p><p>We use shouldFetchVenues in combination with state.last4sqCall and API_DEBOUNCE_TIME to avoid calling the API too often. Every 2 seconds seemed like a good compromise.</p><p>In venuesQuery we use query-string to turn an object into a URL query. It’s one of those things that looks easy, but is much better left as somebody else’s problem</p><p>Great, we fetch recommendations, put them in state, and trigger a re-render. Time to draw them on our map.</p><h3>Put markers on your map</h3><p>To put our recommendations on the map, we add them to RecommendationsMap in a loop. Like this:</p><pre>./components/RecommendationsMap.js<br><br>const RecommendationsMap = ({ mapRegion, gpsAccuracy, recommendations, lookingFor,<br>                              headerLocation, onRegionChange }) =&gt; (<br><br>    &lt;MapView.Animated region={mapRegion}<br>                      style={styles.fullscreen}<br>                      onRegionChange={onRegionChange}&gt;<br>        // ...<br><br>        {recommendations.map(r =&gt; &lt;Recommendation {...r} key={r.venue.id} /&gt;)}<br><br>    &lt;/MapView.Animated&gt;<br>);</pre><p>Recommendations come from a prop and get rendered in a loop as Recommendation components. Each Recommendation is a custom marker that shows a picture and a tip when you tap on it.</p><h3>Recommendation component</h3><pre>./components/Recommendation.js<br><br>class Recommendation extends Component {<br>    get photo() {<br>        const photo = this.props.venue.photos.groups[0].items[0];<br><br>        return `${photo.prefix}300x500${photo.suffix}`;<br>    }<br><br>    render() {<br>        const { venue, tips } = this.props;<br><br>        return (<br>            &lt;MapView.Marker coordinate={{latitude: venue.location.lat,<br>                                         longitude: venue.location.lng}}&gt;<br><br>                &lt;MapView.Callout&gt;<br>                    &lt;Card&gt;<br>                        &lt;Image styleName=&quot;medium-wide&quot;<br>                               source={{uri: this.photo}} /&gt;<br>                        &lt;View styleName=&quot;content&quot;&gt;<br>                            &lt;Subtitle&gt;{venue.name}&lt;/Subtitle&gt;<br>                            &lt;Caption&gt;{tips ? tips[0].text : &#39;&#39;}&lt;/Caption&gt;<br>                        &lt;/View&gt;<br>                    &lt;/Card&gt;<br>                &lt;/MapView.Callout&gt;<br>            &lt;/MapView.Marker&gt;<br>        )<br>    }<br>}</pre><p>MapView.Marker and MapView.Callout come from the react-native-maps library. The first is a pin we show on the map, and the second is a tooltip that shows up when a user taps a marker.</p><p>Inside the tooltip we use a Shoutem Toolkit Card, with an image, a subtitle, and a caption. I took the markup from the <a href="http://shoutem.github.io/docs/ui-toolkit/components/cards">Shoutem Toolkit docs</a> because I like how it looks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w1azbEQ9QrtfFt8c.png" /><figcaption>Shoutem UI Toolkit Card</figcaption></figure><p>Each shows the venue’s photo and the top voted tip. Foursquare’s explore API conveniently gives us both. It gives us a bunch of other info as well, but when I played around, it got crowded really fast. I suggest console.log-ing the props and seeing what’s available.</p><p>Your app should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*63Xy9rt_R-tMq9uX.png" /></figure><p>Now I don’t know why the Pinecrest Diner is open at 3am, but it’s making me hungry. You’ll see more stuff at a more reasonable hour. 🙂</p><p>If that didn’t work, <a href="https://github.com/shoutem/school/tree/master/LunchSpotApp/components">consult the Github</a>.</p><h3>Render topic buttons</h3><p>For the final touch, we give users some options. You won’t always feel like having drinks in the evening and coffee in the morning.</p><p>The logic is a single function in App and the rendering happens <em>also</em> in App. We’ll put the helper components in a Topics.js file.</p><pre>./components/App.js<br><br>class App extends Component {<br>   // ...<br>   <br>   onTopicSelect(lookingFor) {<br>        this.fetchVenues(this.state.mapRegion, lookingFor);<br><br>        this.setState({<br>            lookingFor: lookingFor<br>        });<br>    }<br><br>    render() {<br>        const { mapRegion, lookingFor } = this.state;<br><br>        if (mapRegion) {<br>            return (<br>                &lt;Screen&gt;<br>                    // ...<br>                    {!lookingFor ? &lt;OverlayTopics onTopicSelect={this.onTopicSelect.bind(this)} /&gt;<br>                                 : &lt;BottomTopics onTopicSelect={this.onTopicSelect.bind(this)} /&gt;}<br>                &lt;/Screen&gt;<br>            );<br>        }else{<br>            // ..<br>        }<br>    }<br>}</pre><p>The onTopicSelect callback updates state with a new lookingFor value and triggers a re-render. We use it as the onPress callback on every button.</p><p>In the render method, we use two types of “list of buttons” views. One is a fullscreen overlay, another is a small toolbar under the map.</p><p>They look like this:</p><pre>./components/Topics.js<br><br>const TOPICS = [&#39;food&#39;, &#39;drinks&#39;, &#39;coffee&#39;, &#39;shops&#39;, &#39;sights&#39;, &#39;arts&#39;];<br><br>const OverlayTopics = ({ onTopicSelect }) =&gt; (<br>    &lt;Overlay styleName=&quot;fill-parent&quot;&gt;<br>        &lt;Heading style={{marginBottom: 15}}&gt;What do you feel like?&lt;/Heading&gt;<br>        {TOPICS.map(topic =&gt; (<br>            &lt;Button onPress={() =&gt; onTopicSelect(topic)} key={topic} style={{marginBottom: 10}}&gt;<br>                &lt;Text&gt;{topic}&lt;/Text&gt;<br>            &lt;/Button&gt;<br>        ))}<br>    &lt;/Overlay&gt;<br>);<br><br>const BottomTopics = ({ onTopicSelect }) =&gt; (<br>    &lt;View styleName=&quot;horizontal&quot;&gt;<br>        {TOPICS.map(topic =&gt; (<br>            &lt;Button onPress={() =&gt; onTopicSelect(topic)} key={topic} styleName=&quot;muted&quot;&gt;<br>                &lt;Text&gt;{topic}&lt;/Text&gt;<br>            &lt;/Button&gt;<br>         ))}<br>    &lt;/View&gt;<br>);</pre><p>I took the list of topics from Foursquare’s documentation. They hint that there’s more, but these 6 should cover our bases 🙂</p><p>The components you see here are all from the Shoutem UI Toolkit. Overlay makes a fullscreen overlay with a darkened background, Button makes a nice button, and Heading looks like a big title.</p><p>With that our app is complete. I’d use it find good lunch, would you?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*X-QWm99ZBIhvJ5evxXG4_w.gif" /></figure><p>What do you wanna build next? <a href="/service/mailto:hi@swizec.com?subject=Build+this+app">Email me</a>, I read everything.</p><p><em>Originally published at </em><a href="http://school.shoutem.com/lectures/geolocation-app-react-native/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc05de70811" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/build-a-lunch-recommendation-app-react-native-school-fdc05de70811">Build a lunch recommendation app — 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[Build an Imgur Client with React Native and MobX — React Native School]]></title>
            <link>https://medium.com/react-native-development/build-an-imgur-client-with-react-native-and-mobx-react-native-school-53146d648250?source=rss-690194f3df50------2</link>
            <guid isPermaLink="false">https://medium.com/p/53146d648250</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Shoutem]]></dc:creator>
            <pubDate>Wed, 01 Mar 2017 16:02:05 GMT</pubDate>
            <atom:updated>2017-03-01T16:20:56.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2lKIT2Osxdmwr0zQy5Ffw.png" /></figure><p>Today, we’re building an Imgur app. A supreme fullscreen image browsing experience to make your 💩 even more fun.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5AMQaWaqjyA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5AMQaWaqjyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5AMQaWaqjyA%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7c9f8257a48927ac1a6e2cc8de8cd7c/href">https://medium.com/media/c7c9f8257a48927ac1a6e2cc8de8cd7c/href</a></iframe><p>What, you don’t Imgur while you poop? I do. And so does everyone I know… okay, some only browse Facebook and Twitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*JuIU4ZllF-8Ult5O.gif" /></figure><p>A fullscreen view of Imgur’s frontpage. Tap on the right for next pic, left for the previous. Albums scroll up and down. It’s like Snapchat, but for the Imgur gallery.</p><p>OMG, please put that on the app store! I <em>hate</em> the current mobile experience.</p><p>~ Girlfriend when I showed her the app</p><p>Things that you can’t do: post or favorite or like. But how often do you <em>really</em> do that? 99% of the time, I just scroll through images and waste my time 😇</p><p>Here’s what you’ll learn in today’s lecture:</p><ul><li>how to use MobX for state management</li><li>how to talk to RESTful APIs</li><li>how to render fullscreen images in a ListView</li><li>an elegant way to detect device orientation</li></ul><p>New to React Native? Check out <a href="http://school.shoutem.com/lectures/react-native-101-build-first-mobile-app/">React Native 101</a> where you can build your first native app in 46 lines of code.</p><p>To keep this lecture shorter, the code samples might skip some details. You can see the full code at my <a href="https://github.com/Swizec/ImgurApp">Swizec/ImgurApp Github repository</a>.</p><p>Commits roughly follow this lecture, except there’s some final cleanup to make the source easier for you to read 😁</p><p>You can also watch me build ImgurApp from scratch on my <a href="https://www.liveedu.tv/swizec/">LiveEdu channel</a> if you’re curious 👉 <a href="https://www.liveedu.tv/swizec/videos/NYaYA-an-imgur-app-with-react-native-2">part1</a> | <a href="https://www.liveedu.tv/swizec/videos/PQk91-an-imgur-app-with-react-native-3">part2</a>.</p><p>We start our app the usual way with</p><pre>$ react-native init ImgurApp</pre><h3>Set up MobX for state management</h3><p>ImgurApp is complex enough to use a state management library. Putting state in a central store makes our app easier to reason about, which makes development faster and our lives easier.</p><p>Having a central store that all components have access to also makes our app more flexible. We can move components around without having to rewire all the business logic as well.</p><p>Two popular approaches for state management exist: Redux and MobX. Both have their strengths and weaknesses. Redux is more obvious and closely follows React’s core principles, while MobX requires less code and looks more object-y.</p><p>I like to use MobX because of the “less code” aspect. If you use MobX the way I’m about to show you, it gives you all the same assurances about faux immutability as Redux and could, in theory, support time traveling debugging and all those cool things.</p><p><strong>Install MobX</strong></p><p>We need decorators to use MobX effectively. You <em>can</em> use it without decorators, but I think decorators improve your experience by a lot.</p><p>You can think of decorators as an easier way to write higher order functions and classes. Make a function and use @ to wrap it around anything. You can even use them to make <a href="https://swizec.com/blog/using-hocs-dry-code/swizec/7297">higher order React components</a>.</p><p>But decorators are still stage-0, so we have to enable them.</p><p>First, we install MobX and decorator support for react-native.</p><pre>$ react-native install mobx<br>$ react-native install mobx-react<br>$ react-native install babel-preset-react-native-stage-0</pre><p>I recommend installing libraries through react-native install. It works for all npm packages and ensures the libraries are correctly linked into your project. You never have to open XCode 🙂</p><p>With the libraries installed, we add decorators to our .babelrc presets. Like this:</p><pre>// .babelrc<br>{<br>&quot;presets&quot;: [&quot;react-native&quot;, &quot;react-native-stage-0/decorator-support&quot;]<br>}</pre><p>Your app now supports decorators. 🙌🏼</p><p><strong>MobX 101</strong></p><p>Explaining MobX in detail is beyond the scope of this article, so here’s a quick rundown of the concepts we’re going to use:</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</p><p>@observer – a component whose render() method observes values</p><p>@computed – a method whose value can be fully derived from observables</p><p>@action – a method that changes state, analogous to a Redux reducer</p><p>@inject – a decorator that injects global stores into a component’s props</p><p>That’s basically 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><p>Fullscreen images with device orientation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*QMaZ0lzU35o-OBbZ.gif" /></figure><p>For a better viewing experience, we want images to be full screen. None of the social and branding cruft the default Imgur app comes with.</p><p>But image dimensions don’t always (ever) match your phone’s dimensions, so we have to make a choice. Either the image is full screen and cropped, or it has borders and you can see the full thing.</p><p>An approach many apps follow is to use borders in portrait mode and full screen in landscape. We’re going to do the same.</p><p>For that we need:</p><ul><li>a MobX store to save orientation</li><li>a way to change this value when orientation changes</li><li>different image styles for the two orientations</li></ul><h3>Setup the global MobX Store</h3><p>A MobX store can be any class with observable properties. Ours is called Store and sits in ./Store.js.</p><p>To store device orientation, it needs a property and an action. Because we’re reusing the touchable image component from <a href="http://school.shoutem.com/lectures/react-native-101-build-first-mobile-app/">our last lecture</a>, we also stub out prevImage and nextImage actions. It avoids undefined callbacks 🙂</p><pre>// ./Store.js<br>import { observable, action } from &#39;mobx&#39;;<br>import { PORTRAIT } from &#39;./Constants&#39;;<br><br>class Store {<br>    @observable orientation = PORTRAIT;<br><br>    @action changeOrientation(orientation) {<br>        this.orientation = orientation;<br>    }<br><br>    @action prevImage() {<br>        console.log(&#39;previous&#39;);<br>    }<br><br>    @action nextImage() {<br>        console.log(&#39;next&#39;);<br>    }<br>}<br><br>export default new Store();</pre><p>We import observable and action decorators from mobx, get a relevant constant from Constants, and set up a class with an observable and some actions. The Constants file is a convenient way to store the constants we’re using all over our app. You can see it on Github <a href="https://github.com/Swizec/ImgurApp/blob/34d2e54e6bffeb189b507b73912f624e4e6e2c5c/Constants.js">here</a>.</p><p>Notice that we’re exporting an instance, not a class. This ensures that no matter who imports our Store, they all share the same instance.</p><p><strong>Detect device orientation</strong></p><p>The most elegant way I’ve found to detect device orientation is to hook into the onLayout callback on your main &lt;View&gt;. It triggers every time your app changes layouts.</p><p>We can also take this opportunity to set up our Store so our components have access to it through @inject(&#39;store&#39;). We’ll use MobX’s Provider component for that.</p><pre>// ./index.ios.js<br><br>import { Provider as MobXProvider, observer } from &#39;mobx-react/native&#39;;<br><br>import ImgurCarousel from &#39;./components/ImgurCarousel&#39;;<br>import { LANDSCAPE, PORTRAIT } from &#39;./Constants&#39;;<br>import Store from &#39;./Store&#39;;<br><br>@observer<br>class ImgurApp extends Component {<br>    onLayout(event) {<br>        const { width, height } = event.nativeEvent.layout;<br>        const orientation = ( width &gt; height ) ? LANDSCAPE : PORTRAIT;<br><br>        Store.changeOrientation(orientation);<br>    }<br><br>    render() {<br>        return (<br>            &lt;MobXProvider store={Store}&gt;<br>                &lt;View style={styles.container}<br>                      onLayout={this.onLayout.bind(this)}&gt;<br>                    &lt;ImgurCarousel /&gt;<br>                &lt;/View&gt;<br>            &lt;/MobXProvider&gt;<br>        );<br>    }<br>}</pre><p>We gut the ImgurApp.render method given by the default app init and replace it with &lt;MobXProvider .... The provider puts all its props into a <a href="https://facebook.github.io/react/docs/context.html">React context</a>, which makes them globally available.</p><p>This is safe to do because MobX has a mechanism that ensures changes propagate to all observers as long as you don’t forget to mark them as observers. I’ve had many fun debugging hours that way 😅</p><p>In the onLayout callback, we compare width and height then call the changeOrientation action with the appropriate orientation. LANDSCAPE when the screen is wider than it is high, PORTRAIT otherwise.</p><p><strong>Render a fullscreen image</strong></p><p>Now let’s make the ImgurCarousel component. It’s the component that renders our entire interface.</p><p>Why isn’t it in index.ios.js then? Because we can share it between both iOS and Android. There’s nothing device specific in there.</p><p>At first, we make it render a static TouchableImage so you can see how the fullscreen-ness works. We’ll expand it later when we start loading images from Imgur.</p><p><strong>ImgurCarousel</strong></p><pre>// ./components/ImgurCarousel.js<br><br>@inject(&#39;store&#39;) @observer<br>class ImgurCarousel extends Component {<br>    render() {<br>        const { image, store } = this.props;<br><br>        return (<br>            &lt;TouchableImage image={{link: &quot;https://i.imgur.com/6cFNnJp.jpg&quot;,<br>                                   title: &quot;Its my cake day, why am i happier about this then my real birthday, i will never know. First fav. Post&quot;}} /&gt;<br>        );<br>    }<br>}</pre><p>ImgurCarousel renders a single TouchableImage and gives it an image with a title. Yes, it looks silly right now, but it’s going to decide between Album, TouchableImage, or Spinner later on.</p><p><strong>TouchableImage</strong></p><p>The TouchableImage component is pillaged from our <a href="http://school.shoutem.com/lectures/react-native-101-build-first-mobile-app/">previous lecture</a>. It renders an image and calls different callbacks based on where you tap.</p><pre>// ./components/TouchableImage.js<br><br>@inject(&#39;store&#39;) @observer<br>class TouchableImage extends Component {<br>    state = {<br>        width: null<br>    }<br><br>    onPress(event) {<br>        const { width } = this.state,<br>              { store } = this.props,<br>              X = event.nativeEvent.locationX;<br><br>        if (X &lt; width/2) {<br>            store.prevImage();<br>        }else{<br>            store.nextImage();<br>        }<br>    }<br><br>    onImageLayout(event) {<br>        this.setState({<br>            width: event.nativeEvent.layout.width<br>        });<br>    }<br><br>    get caption() {<br>        let { caption, image } = this.props;<br>        return image.title || image.description || caption;<br>    }<br><br>    render() {<br>        const { image, orientation } = this.props,<br>                    uri = image.link.replace(&#39;http://&#39;, &#39;https://&#39;);<br><br>        return (<br>            &lt;TouchableHighlight onPress={this.onPress.bind(this)}<br>                                style={styles.fullscreen}&gt;<br>                &lt;Image source={{uri: uri}}<br>                       style={[styles.backgroundImage, styles[orientation.toLowerCase()]]}<br>                       onLayout={this.onImageLayout.bind(this)}&gt;<br>                    &lt;Text style={styles.imageLabel}&gt;{this.caption}&lt;/Text&gt;<br>                &lt;/Image&gt;<br>            &lt;/TouchableHighlight&gt;<br>        );<br>    }<br>}</pre><p>Very similar, right? We use onLayout to store width in local state (yes, it’s still fine even with MobX), then use it to call either prevImage or nextImage.</p><p>We use TouchableHighlight to detect taps and give feedback to the user, Image to render the image, and Text to render the caption. A caption can be either image.caption, image.title, or a caption forced through props.</p><p>This is forward-looking to match Imgur’s API.</p><p>A nice feature of using a store to manage state is that TouchableImage has direct access to it. If we want anything from the store, like the orientation, we get it with store.&lt;property&gt;. To trigger actions, we call them like normal functions.</p><p>An important thing to do is make sure we’re loading only https images. iOS blocks them otherwise, and Imgur’s API returns nonhttps links.</p><p><strong>Styles for fullscreen</strong></p><p>The key to making our image full screen lies in the styling. We move styles out of index.ios.js and put them in ./components/styles.js. That makes styles easier to share across files.</p><p>You can see the full <a href="https://github.com/Swizec/ImgurApp/blob/2e5963366fbfa1e6b8ba5bcc3edb3aefefacd98a/components/styles.js">styles.js file on Github</a>. These are the relevant parts:</p><pre>// ./components/styles.js<br><br>const styles = StyleSheet.create({<br>    fullscreen: {<br>        flex: 1,<br>        width: null,<br>        height: null<br>    },<br>    backgroundImage: {<br>        flex: 1,<br>        justifyContent: &#39;flex-end&#39;,<br>        width: null,<br>        height: null<br>    },<br>    portrait: {<br>        resizeMode: &#39;contain&#39;<br>    },<br>    landscape: {<br>        resizeMode: &#39;cover&#39;<br>    },</pre><p>We propagate flex: 1 all the way down to the image itself, ensure width and height are null, then use different resize modes. For portrait we contain the image, and for landscape we resize it to cover the full screen.</p><p>This works great for single images. In the ListView step, we’ll have to add logic to the height so it doesn’t try to render them all on the same screen. You’ll see.</p><p>You should now have an app that shows a guy with soap bubbles on his face.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*aLfgEKFWDL9p4AWv.gif" /></figure><h3>Reading Imgur’s REST API</h3><p>The public parts of Imgur’s API are relatively easy to use. We care about two endpoints:</p><ul><li>https://api.imgur.com/3/gallery/hot/viral/&lt;N&gt;</li><li>https://api.imgur.com/3/album/&lt;albumID&gt;</li></ul><p>The first returns images from the front page. The N argument lets us page through them 60 images at a time.</p><p>The second returns images for a specific album. We need it because a lot of Imgur posts are collections of multiple images.</p><p>We’re going to talk to this API using <a href="https://swizec.com/blog/a-tiny-es6-fetch-wrapper/swizec/7177">my </a><a href="https://swizec.com/blog/a-tiny-es6-fetch-wrapper/swizec/7177">better-fetch wrapper</a> of ES6’s built in fetch() function. It makes API calls with common Authorization headers easier.</p><p>If you don’t know about fetch(), I suggest reading <a href="https://davidwalsh.name/fetch">David Walsh’s excellent article</a> that explains how it works. While fetch() hasn’t yet reached wide adoption on the web, it’s <em>the</em> way to do REST in React Native.</p><p><strong>Install helper libs</strong></p><p>You’ll need better-fetch and the babel-latest-preset preset for this. I assume the preset is needed because of something I did in my library code, not because of fetch() itself.</p><pre>$ react-native install better-fetch<br>$ react-native install babel-preset-latest</pre><p>This gives you both libraries and links them. You have to enable the preset in .babelrc.</p><pre>// ./.babelrc<br>{<br>&quot;presets&quot;: [&quot;react-native&quot;, &quot;latest&quot;, &quot;react-native-stage-0/decorator-support&quot;]<br>}</pre><p>Ordering is important. Your build will fail if latest shows up after react-native-stage-0. I don’t know why, but I’m happy that somebody told me when I livecoded this app.</p><p><strong>Set up Imgur auth key</strong></p><p>My better-fetch lets us set up default headers that are re-used on every API call. This is perfect for authorization headers.</p><pre>// ./Store.js<br><br>import fetch from &#39;better-fetch&#39;;<br><br>fetch.setDefaultHeaders({<br>    Authorization: `Client-ID ${CLIENT_ID}`<br>});</pre><p>Now every API call we make is going to have that Authorization header. This is good enough for <em>reading</em> Imgur’s API. We’d have to do the entire <a href="https://api.imgur.com/oauth2">OAuth dance</a> to allow <em>writing</em>. Which is why we don’t 🙂</p><p><a href="https://api.imgur.com/">Register your app</a> on Imgur to get your CLIENT_ID. You’ll need an account and some URLs. I used the Github repository URLs because I don’t care about OAuth.</p><p>You can use my ID if you promise not to do anything shady.</p><p><strong>Actions for reading Imgur</strong></p><p>We need to expand our Store with some actions for fetching images. Another benefit of using state management: All our business logic is in one place.</p><pre>// ./Store.js<br><br>class Store {<br>    @observable images = [];<br>    @observable index = 0;<br>    @observable galleryPage = 0;<br>    @observable albums = new observable.map();<br>    // ...<br><br>    @action fetchImages() {<br>        fetch(`${IMGUR_URL}gallery/hot/viral/${this.galleryPage}`)<br>          .then(fetch.throwErrors)<br>          .then(res =&gt; res.json())<br>          .then(json =&gt; {<br>              json.data.forEach(img =&gt; this.images.push(img));<br>          })<br>          .catch(err =&gt; console.log(&#39;ERROR&#39;, err.message));<br>    }<br><br>    @action fetchAlbum(id) {<br>        if (!this.albums.has(id)) {<br>            fetch(`${IMGUR_URL}album/${id}`)<br>              .then(fetch.throwErrors)<br>              .then(res =&gt; res.json())<br>              .then(json =&gt; {<br>                  this.albums.set(json.data.id, json.data);<br>              })<br>              .catch(err =&gt; console.log(&#39;ERROR&#39;, err.message, err));<br>        }<br>    }<br>}</pre><p>Oh my, a lot of state showed up. We use images to keep a list of loaded images, copied straight from the API. index and galleryPage help us keep track of where in the images array we are, and albums is a hash map of albums. That is, images with multiple images.</p><p>We use a hash map for the albums so it’s easier to avoid unnecessary fetching.</p><p>fetchImages calls the Imgur API, gets the currentPage of gallery results and adds them to images. Looping through the result and adding them one-by-one ensures MobX observers keep working correctly.</p><p>fetchAlbum does something similar except it gets a specific album from the API and adds it to the hash map. A conditional check ensures that we never fetch the same album twice, which speeds up our app.</p><p><strong>Make sure you call fetchImages</strong></p><p>A quick intermezzo while we set up image loading: Call fetchImages when your app first loads.</p><pre>// ./index.ios.js<br><br>class ImgurApp extends Component {<br>    // ...<br>    componentWillMount() {<br>        Store.fetchImages();<br>    }<br>}</pre><p>MobX will call the correct observers when fetchImages is done loading images and updating the images array.</p><p><strong>Actions that traverse images</strong></p><p>Now that we have a local images array, we can implement the prevImage and nextImage stubs from before. They increase or decrease the index and fetch the next page of results as necessary.</p><p>We also add a @computed value that tells us the current image.</p><pre>// ./Store.js<br><br>    @action prevImage() {<br>        this.index = this.index - 1;<br><br>        if (this.index &lt; 1) { this.index = 0; } } @action nextImage() { this.index = this.index + 1; if (this.index &gt; this.images.length) {<br>            this.galleryPage = this.galleryPage+1;<br>            this.fetchImages();<br>        }<br>    }<br><br>    @computed get currentImage() {<br>        return this.images.length ? this.images[this.index] : null;<br>    }</pre><p>With these implemented, and TouchableImage already wired up, we automagically enable traversing the Imgur gallery. We just have to update ImgurCarousel to use store.currentImage.</p><p><strong>Render Imgur pics</strong></p><p>As promised, the only change we ned is in ImgurCarousel.</p><pre>// ./components/ImgurCarousel.js<br><br>@inject(&#39;store&#39;) @observer<br>class ImgurCarousel extends Component {<br>    render() {<br>        const { store } = this.props;<br><br>        if (!store.currentImage) {<br>            return null;<br>        }<br><br>        return (<br>            &lt;TouchableImage image={store.currentImage} /&gt;<br>        );<br>    }<br>}</pre><p>An empty currentImage means we’re still waiting for an API response. This is where we’ll render a loading spinner later.</p><p>If the image is there, we render it with TouchableImage. Unfortunately, that component can’t handle albums, so many images show up as a blank screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*yXZ3bQuReXZjjG6D.gif" /></figure><h3>Render albums in a ListView</h3><p>Now comes the fun part: Rendering an album of images in a scrollable ListView. The &lt;Album&gt; component.</p><p>The Album component is made of 3 parts:</p><ul><li>some logic to call store.fetchAlbum when necessary</li><li>some logic to build a ListView dataSource</li><li>3 rendering functions: renderRow, renderHeader, and render</li></ul><h3>Fetch Album</h3><p>Album fetching happens when our component is first render or its albumID property updates.</p><pre>// ./components/Album.js<br><br>@inject(&#39;store&#39;) @observer<br>class Album extends Component {<br>    componentWillMount() {<br>        const { store, albumID } = this.props;<br><br>        store.fetchAlbum(albumID);<br>    }<br><br>    componentWillReceiveProps(newProps) {<br>        const { store, albumID } = newProps;<br><br>        store.fetchAlbum(albumID);<br>    }</pre><p>In both cases, we defer to store.fetchAlbum and rely on its ability to avoid double-fetching. When the album is ready in store.albums, MobX’s observer wiring will take over and call our render method.</p><p>This is why I like MobX: A lot of sophistication with very little code to write 🙂</p><p><strong>Build dataSource</strong></p><p>ListView components render from a dataSource that’s more complex than a plain array. I don’t know the details of how it works, but I do know how to make one.</p><pre>// ./components/Album.js<br><br>@inject(&#39;store&#39;) @observer<br>class Album extends Component {<br>    // ...<br>    get dataSource() {<br>        const { store, albumID } = this.props,<br>              ds = new ListView.DataSource({<br>                  rowHasChanged: (r1, r2) =&gt; r1.id !== r2.id<br>              });<br><br>        return ds.cloneWithRows(toJS(this.album.images));<br>    }<br><br>    get album() {<br>        const { store, albumID } = this.props;<br><br>        return store.albums.get(albumID);<br>    }</pre><p>We instantiate a new ListView.DataSource with a row comparator function. We use cloneWithRows to fill it with data.</p><p>The toJS function we used is a MobX method that converts deep observable objects into plain JavaScript. This helps cloneWithRows read what we’re giving it.</p><p>The album() getter gets a specific album from the Store albums hash map. We use it as a helper method because similar code shows up in a few places.</p><p><strong>Render</strong></p><p>Rendering the ListView happens in 3 functions. The main render() method renders the ListView itself, and two helper methods render specific parts of the view.</p><pre>renderRow(img, caption) {<br>        const { store } = this.props;<br><br>        let height = store.screenSize.height;<br><br>        if (img.height &lt; height) {<br>            height = img.height;<br>        }<br><br>        return (<br>            &lt;TouchableImage image={img}<br>                            height={height}<br>                            caption={caption} /&gt;<br>        )<br>    }<br><br>    renderHeader() {<br>        return (<br>            &lt;Text style={styles.header}&gt;{this.album.title}&lt;/Text&gt;<br>        );<br>    }<br><br>    render () {<br>        const { store, albumID } = this.props,<br>              album = this.album;<br><br>        if (album) {<br>            if (album.images.length &gt; 1) {<br>                return (<br>                    &lt;View style={styles.fullscreen}&gt;<br>                        &lt;ListView dataSource={this.dataSource}<br>                                  renderRow={img =&gt; this.renderRow(img)}<br>                                  renderHeader={this.renderHeader.bind(this)}<br>                                  style={styles.fullscreen} /&gt;<br>                    &lt;/View&gt;<br>                );<br>            }else{<br>                return this.renderRow(album.images[0], album.title);<br>            }<br>        }else{<br>            return null;<br>        }<br>    }</pre><p>renderRow renders a specific ListView row. In this case a single TouchableImage with a fixed height and [maybe] caption. The fixed height helps us stretch rows to full screen size. I’ll show you how in a bit.</p><p>renderHeader renders an album header, which is just a &lt;Text&gt; element with bigger font. It shows up at the top of the screen.</p><p>render renders a fullscreen View with a fullscreen ListView. We give the ListView our dataSource and the two render helpers.</p><p>The result is a whole album squeezed onto the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*AQnCxnXVINZ_yywK.png" /></figure><h3>Fullscreen ListView rows</h3><p>To stretch ListView rows to full height, we need to save screenSize information then use it in TouchableImage. We already set up renderRow above to set the height either based on screen size or on image size depending on what looks better.</p><p><strong>First</strong>, we need to add an observable and an action to Store.</p><pre>// ./Store.js<br>class Store {<br>    // ...<br><br>    @observable screenSize = {<br>        width: null,<br>        height: null<br>    };<br><br>    @action updateScreenSize(width, height) {<br>        this.screenSize.width = width;<br>        this.screenSize.height = height;<br>    }</pre><p>That’s a screenSize object with a width and a height and an action that updates it. Make sure you don’t do something like this.screenSize = { .... That creates a new object and messes with MobX’s observables.</p><p><strong>Second</strong>, we add a call to updateScreenSize in the main ImgurApp component. Right where we save orientation.</p><pre>// ./index.ios.js<br><br>class ImgurApp extends Component {<br>    onLayout(event) {<br>        const { width, height } = event.nativeEvent.layout;<br>        const orientation = ( width &gt; height ) ? LANDSCAPE : PORTRAIT;<br><br>        Store.changeOrientation(orientation);<br>        Store.updateScreenSize(width, height);<br>    }<br><br>// ...<br>}</pre><p><strong>Third</strong>, we have to use the height prop in our TouchableImage component. Find the render method and add to Image‘s style prop.</p><pre>class TouchableImage extends Component {<br>    // ...<br>    render() {<br>        const { image, store, height } = this.props,<br>              uri = image.link.replace(&#39;http://&#39;, &#39;https://&#39;);<br><br>        return (<br>            // ...<br>                &lt;Image source={{uri: uri}}<br>                       style={[styles.backgroundImage,<br>                               styles[store.orientation.toLowerCase()],<br>                               {height: height || null}]}<br>                       onLayout={this.onImageLayout.bind(this)}&gt;<br>                    //...</pre><p>If height is given, we use it, otherwise we keep the null from styles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*LsXiGACV_icmcsq_gUhtLA.gif" /></figure><h3>Add a loading spinner</h3><p>Looking at a blank screen while images load is annoying. A pretty beating heart from <a href="http://loading.io/">loading.io</a> makes it easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*ZYnrxxhnrVYnNq74.gif" /></figure><p>A Spinner component is a fullscreen view that centers its children and an Image from a local file. The only way to get those in React Native is to use require().</p><pre>const Spinner = () =&gt; (<br>    &lt;View style={[styles.fullscreen, styles.centered]}&gt;<br>        &lt;Image source={require(&#39;./img/heart.gif&#39;)}<br>               style={{width: 100, height: 100}} /&gt;<br>    &lt;/View&gt;<br>);</pre><p>The fullscreen and centered styles come from style.js and look like this:</p><pre>const styles = StyleSheet.create({<br>    fullscreen: {<br>        flex: 1,<br>        width: null,<br>        height: null<br>    },<br>    centered: {<br>        justifyContent: &#39;center&#39;,<br>        alignItems: &#39;center&#39;<br>    },<br><br>    // ...</pre><p>Then you replace instances of return null in ImgurCarousel and Album, and that’s your final touch. Users see a green beating heart while they wait for Imgur to respond.</p><p><a href="http://eepurl.com/cxTnOL">Subscribe with your email</a> to get the next lecture in your inbox. We’re building an app to explore local restaurants on a map.</p><p>Got an app you want to see built? <a href="/service/mailto:hi@swizec.com?subject=I%20have%20an%20app%20idea">Email me</a>.</p><p><em>Originally published at </em><a href="http://school.shoutem.com/lectures/build-simple-imgur-client-react-native/"><em>school.shoutem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53146d648250" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-development/build-an-imgur-client-with-react-native-and-mobx-react-native-school-53146d648250">Build an Imgur Client with React Native and MobX — 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>