<?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 Marcel Kalveram on Medium]]></title>
        <description><![CDATA[Stories by Marcel Kalveram on Medium]]></description>
        <link>https://medium.com/@marcelkalveram?source=rss-8cf85b05864c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8wAQ5wN-EYFlw7aQLJG0jA.jpeg</url>
            <title>Stories by Marcel Kalveram on Medium</title>
            <link>https://medium.com/@marcelkalveram?source=rss-8cf85b05864c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:43:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcelkalveram/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[AI and the future of product engineering]]></title>
            <link>https://marcelkalveram.medium.com/ai-and-the-future-of-product-engineering-240a8e6b6fe7?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/240a8e6b6fe7</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[product-engineer]]></category>
            <category><![CDATA[product-development]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 09:31:55 GMT</pubDate>
            <atom:updated>2024-10-01T09:34:40.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XmWxuI7LdR8mVRGN1kQWQ.jpeg" /><figcaption>Image generated by DALL·E</figcaption></figure><p>In this post, I’d like to explore the role of the software engineer in the world of product development, how it is impacted by AI, and what we can expect from this transformation.</p><h3>TL;DR</h3><ul><li>AI enables engineers to spend less time on mundane tasks, freeing up their time for tasks AI cannot automate yet</li><li>AI-enabled engineers with product experience — similar to indie hackers — take part in the whole product development lifecycle</li><li>Hiring product engineers is a resource-efficient way for companies — especially startups — to build products users want</li></ul><h3>Engineering and AI</h3><p>I don’t think AI is going to replace software engineers. But since it enables us to automate many chores, we can dedicate more time to tasks that matter, such as solving real user pain points.</p><p>The shift from purely writing software to spending more time on the product and its users already gave rise to a role that’s gaining a lot of traction: the product engineer.</p><h4>What exactly is a product engineer?</h4><p>Let me quote the definition provided by the team at <a href="https://posthog.com/blog/what-is-a-product-engineer">Posthog</a>:</p><blockquote>A product engineer, at its most basic, is a software engineer building products. They do similar work to software engineers: writing code and shipping features. […] What makes them unique is their focus on creating a product for users.</blockquote><p>I would even go as far as saying that product engineers are the indie hackers of the modern startup. They don’t only know how to deliver software but also care deeply about validating it against the market.</p><p>This role becomes even more exciting with the rise of AI. Let’s explore why!</p><h3>AI makes coding cheaper</h3><p>AI can write pretty good code and returns complex algorithms based on prompts that take a fraction of the time to write.</p><p>Of course, the output often contains bugs, and debugging them is a lot easier with a strong software development background. AI assistants like <a href="https://github.com/features/copilot">Copilot</a> and <a href="https://www.cursor.com/">Cursor AI</a> obviously speed this process up significantly.</p><p>Also, AI development could reinforce biases and automate bad practices if not closely monitored. But let’s imagine a world where all of this has been perfected to a point where you rarely have bugs and minimal bias.</p><p>Most programmers should gain a lot of time, time they can spend on high-level architecture, code reviews and fixing bugs.</p><p>The worst case — the dystopia we all fear — is that engineers become obsolete. In an ideal world though, aren’t we now simply able to ship software faster?</p><p>Maybe, but speed doesn’t automatically match better outcomes. You can write new features in less time, but someone still needs to make sure that the product is aligned with users’ actual needs and solve meaningful problems.</p><h3>Say hi to the Product Engineer</h3><p>With their technical expertise and focus on the user the product engineer is well positioned to benefit from this transformation.</p><p>If writing code takes less time, the product engineer can spend more time on other stages of the product development lifecycle, such as user discovery, product strategy and analytics, thus becoming a more holistic product expert.</p><p>Let me dig deeper into what I think the responsibilities of the AI-enabled product engineer of the future might be:</p><h4>Product Discovery</h4><p>Most product development starts at this stage: analysing your users, gathering insights, and understanding the market and your competitors.</p><p>As of now, this doesn’t seem like a task that AI can do autonomously, even though it can aid in the process. It requires:</p><ul><li>Empathy</li><li>Real conversations</li><li>Deep insights analysis</li></ul><p>Activities at this stage usually involve lots of calls, whiteboarding, brainstorming sessions and stakeholder meetings.</p><p>Tools like <a href="https://fireflies.ai/">Fireflies.ai</a> are great at accurately transcribing calls and running prompts on the results. I think they’re becoming an indispensable tool in product discovery.</p><p>But interpreting those insights, eliminating bias and errors, and identifying the signal among the noise is a task that requires human reasoning, experience and intuition.</p><h4>Product Strategy</h4><p>While I wouldn’t expect developers to be experts in business strategy, there are enough strategic decisions in the product lifecycle that an engineer has to take on a daily basis.</p><p>It includes:</p><ul><li>Backlog prioritisation</li><li>Defining roadmaps</li><li>Aligning with business</li></ul><p>Doing this requires some degree of business acumen and a lot of product experience. It involves planning, anticipation, and continually re-evaluating priorities.</p><p>While LLM-based tools — like <a href="https://meetsquad.ai/">Squad</a> — can help automate the grunt work and speed up the process, they don’t fully replace the complex decision-making process. That’s where we are still at an advantage because we can feel how certain decisions play out in the future and envision their consequences in the real world.</p><p>Engineers with deep domain knowledge are obviously in a much better position to use their judgment and make good strategic product decisions.</p><h4>Product Delivery</h4><p>Last but not least, I want to cover some technical tasks that I think AI is still struggling with as well:</p><ul><li>Technical architecture</li><li>System design</li><li>Migrations and refactoring</li></ul><p>They require a lot of context around the codebase and its nuances, but also an understanding of the product objectives; Tasks that require reasoning, spatial thinking, and a lot of nitty-gritty configuration work.</p><p>AI is great at supporting us in this process. Tools like <a href="https://www.qodo.ai/">Qodo</a> claim to help developers write, test and review code.</p><p>But it is probably too soon for an AI to autonomously plan, design and deliver bug-free user experiences, or refactor and migrate large parts of a codebase, especially when a system is highly distributed and complex.</p><h3>A glimpse into the future</h3><p>Product engineers are well-positioned to tackle each of these areas. They understand both, the technical implications of product decisions, and can empthasise with users. These skills and the ability to employ AI at each of these steps make them an invaluable asset for any product team aiming to be more resource-efficient.</p><p>This doesn’t mean non-technical people can’t utilise AI to the same extent. Also, UX designers, business analysts, and product managers bring a depth of expertise that engineers, even AI-empowered ones, might not easily acquire. Most often, it’s the discussions between people from diverse roles that lead to the most interesting results.</p><p>However, engineers can use no-code tools more efficiently and build prototypes quickly. Combined with an eye for good design and an intuition for what users want, this is a skill which can accelerate product development significantly. My experience is that people working at the intersection of product and engineering are indispensable team members, and they’re often the <a href="https://www.noidea.dog/glue">glue</a> between business and code.</p><p>Don’t get me wrong. I don’t expect all engineers to become product experts. Despite the advances of AI, there’s still a ton of deep technical expertise required for highly technical roles.</p><p>From a business perspective though, it’s an exciting opportunity: product engineers can contribute at all levels of the product development lifecycle, potentially resulting in less communication overhead and fewer misunderstandings. The upsides are increased productivity, better alignment on user goals and — most importantly — increased user satisfaction.</p><p>If you would like help in understanding the role of the product engineer in more detail, feel free to get in touch <a href="https://www.linkedin.com/in/marcelkalveram/">via LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240a8e6b6fe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Bullet-Proof Approach to Storing Sensitive User Data in React Native]]></title>
            <link>https://medium.com/swlh/a-bullet-proof-approach-to-storing-sensitive-user-data-in-react-native-ab3f7a2779f9?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3f7a2779f9</guid>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 08:27:36 GMT</pubDate>
            <atom:updated>2021-02-20T18:41:31.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vt_QSAYZSpJT2_Mt" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=medium&amp;utm_medium=referral">Franck - Free-Hotspot.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Keeping data on mobile devices secure is crucial if you’re working on a product that stores sensitive information about your user.</p><p><strong>But did you know that by default, the local storage mechanism in React Native (AsyncStorage) is </strong><a href="https://stackoverflow.com/questions/39148714/is-react-natives-async-storage-secure"><strong>unencrypted</strong></a><strong>?</strong></p><p><strong>On iOS</strong>, the main storage library for React Native is based on the Apple File System, using <a href="https://developer.apple.com/documentation/foundation/filemanager">FileManager</a> to read and store files on the device <em>unencrypted</em>.</p><p><strong>On Android</strong>, AsyncStorage uses either the key-value store <a href="https://rocksdb.org/">RocksDB</a> or <a href="https://developer.android.com/training/data-storage/sqlite">SQLite</a>, based on which one is available. The data in there is <em>unencrypted</em>.</p><blockquote><strong>TL;DR — just show me the code!</strong></blockquote><blockquote>The repository is available here. Feel free to fork and raise issues:<br><a href="https://github.com/marcelkalveram/react-native-bulletproof-redux-provider">https://github.com/marcelkalveram/react-native-bulletproof-redux-provider</a></blockquote><h3>A hybrid approach to safely store user data</h3><p>Of course, there is a way on both platforms to store data more securely: <a href="https://developer.apple.com/documentation/security/keychain_services">Keychain</a> and <a href="https://developer.android.com/training/articles/keystore">Keystore</a>, both abstracted away and nicely encapsulated by the powerful library <a href="https://github.com/oblador/react-native-keychain">react-native-keychain</a>.</p><p>But none of them is made for storing <em>huge</em> chunks of data. Here are two bits of context from their respective documentation:</p><blockquote><em>Use </em><strong><em>Keychain</em></strong><em> to securely store </em>small<em> chunks of data on behalf of the user.</em></blockquote><blockquote><em>The </em><strong><em>Keystore</em></strong><em> lets you store </em>cryptographic keys<em> in a container to make it more difficult to extract from the device.</em></blockquote><p>As you can see, not a place where you’d store huge blobs of sensitive data.</p><p>With that in mind, how would we go about combining <strong>Keychain/Keystore</strong> and AsyncStorage to create a hybrid that benefits from the best of both worlds: lots of storage space <em>and</em> ultra-secure encryption?</p><p><strong>Here’s a high-level idea. We’ll go into the implementation details later:</strong></p><ol><li>Create a <strong>secure key</strong> usingreact-native-keychain . That’s the key we’ll use to encrypt our data. 🔑</li><li>Turn our store data into an easily encrypt-able format, ie. using JSON.stringify().</li><li>Encrypt our data using the generated <strong>secure key</strong> 🔐</li><li>Write the encrypted blob of data to our <em>unencrypted</em> store.</li></ol><p>This turns your <em>unencrypted</em> AsyncStorage into a safe vault that can only be unlocked by the person owning that key. In most cases and unless someone got their phone stolen and compromised that’s the primary user of the device.</p><h3>Adding Redux to the mix</h3><p>While this approach can be applied to any storage solution, I’m going to explain how this can be achieved using <strong>Redux</strong>, <strong>Redux Persist</strong> and Redux Persist’s <strong>“Transform Encrypt”</strong> plugin.</p><h4>Leveraging redux-persist</h4><p>With redux-persist, implementing this encryption flow gets a whole lot simpler because the encryption/decryption mechanism can be easily plugged in via the <a href="https://github.com/maxdeviant/redux-persist-transform-encrypt">redux-persist-transform-encrypt</a> plugin.</p><p>The crux here is to <em>not</em> use any randomly generated static key (defined at build time) and could potentially be reverse-engineered and accessed by intruders. Instead, we use a <em>random</em> key that:</p><ul><li>we generate at <em>runtime, </em>when the app gets launched for the first time.</li><li>we store in our secure <strong>Keystore</strong>/<strong>Keychain </strong>vault.</li><li>we reuse for every subsequent use of our app.</li></ul><p>The fact that the secure random key has a high degree of randomness, is not available at build time and can’t be easily guessed or recreated makes the encrypted data in your AsyncStorage <em>much</em> safer, and completely useless to anyone without it.</p><h3>Putting it into practice</h3><p>It’s easier to understand this flow by visualising it at a slightly higher level of abstraction. I’ve split this process up into two “Gate” components, an idea I shamelessly stole from redux-persist(which contains a so-called PersistGate, which we’re also going to talk about briefly later).</p><p>The “Gate” here implies that the component won’t render its children before it hasn’t completed its internal state logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkfqYTXkzBHQIFAQJCs35Q.jpeg" /><figcaption>A high-level overview of the component involved in this <strong>secure storage</strong> mechanism</figcaption></figure><p>Here’s what each of them does:</p><ul><li><strong>EncryptionGate</strong>: takes care of retrieving the secure key</li><li>includes a<strong> key generator </strong>to generate and persist the key on the device. In our example, this is based on react-native-keychain.</li><li><strong>StoreGate</strong>: configures the store, using the secure key for encryption</li><li>includes a <strong>store generator</strong>, similar to a configureStore method for Redux. In our case, we’re using redux-persist for persistence.</li></ul><p><strong>Without further ado, let’s look at the implementation details:</strong></p><h4><strong>&lt;EncryptionGate /&gt;</strong></h4><p>The first component in our encryption flow completes the following tasks:</p><ul><li>retrieves encryption key using a <strong>key generator</strong></li><li>generates an object with two props: an isFresh flag and the securekey.</li><li>passes this object into its children, in our case the StoreGate.</li></ul><p><strong>Here’s the corresponding React code:</strong></p><pre><em>export </em>const<em> </em><strong><em>EncryptionGate</em></strong><em> </em>=<em> </em>({<em>children</em>}) =&gt;<em> </em>{</pre><pre>  const<em> </em>[<em>encryptionKey</em>,<em> setEncryptionKey</em>]<em> </em>=<em> useState</em>({<br>    <em>isFresh</em>:<em> false,<br>    key</em>:<em> null</em>,<br>  });</pre><pre><em>  useEffect</em>(()<em> </em>=&gt;<em> </em><br>    (<em>async </em>()<em> =&gt; </em>{<br>      const<em> </em>{<em>isFresh</em>,<em> key</em>}<em> </em>=<em> await </em><strong><em>getEncryptionKey</em></strong>();<br>      <em>setEncryptionKey</em>({isFresh,<em> </em>key});<br>    })(),<br>  []);</pre><pre>  if<em> </em>(!<em>encryptionKey.key</em>)<em> </em>{<br>    <em>return null</em>;<br>  }</pre><pre><em>  return children</em>(encryptionKey);</pre><pre>};</pre><p>You may have noticed there’s a new function call in here: <strong>getEncryptionKey()</strong><em>. </em>So what’s that?</p><p>This is the place where we generate the persistent <strong>secure key</strong> on the user’s phone. It means that once it’s been generated, this method will return the same key every time until the user deletes the app or resets the phone.</p><p>Before we move on to its implementation details, let’s have a look at how this function fits in to the overall encryption flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2O0I23_BKOZdIUNMd2eUA.jpeg" /><figcaption>Bird’s eye view of the <strong>EncryptionGate</strong> and <strong>getEncryptionKey</strong> method</figcaption></figure><p><strong>Here’s the implementation of the </strong><strong>getEncryptionKey</strong> method<strong>:</strong></p><pre><em>import * as Keychain from &#39;react-native-keychain&#39;;<br>import {generateSecureRandom} from &#39;react-native-securerandom&#39;;<br></em>import binaryToBase64 from &#39;react-native/Libraries/Utilities/binaryToBase64&#39;;</pre><pre>//<em> Unique non-sensitive ID which we use to save the store password<br></em>const<em> ENCRYPTION_KEY </em>=<em> &#39;UNIQUE_ID</em>&#39;;</pre><pre><em>export </em>const<em> </em><strong><em>getEncryptionKey</em></strong><em> </em>=<em> async </em>()<em> </em>=&gt;<em> </em>{</pre><pre>  // check for existing credentials<br>  const<em> existingCredentials </em>=<em> await </em><strong><em>Keychain</em></strong><em>.getGenericPassword</em>();<br>  if<em> </em>(existingCredentials)<em> </em>{<br>    <em>return </em>{ <em>isFresh</em>:<em> false</em>,<em> key</em>:<em> existingCredentials.password </em>};<br>  }</pre><pre>  // generate new credentials based on random string<br>  const<em> randomBytes </em>=<em> await generateSecureRandom</em>(32);<br>  const<em> randomBytesString </em>=<em> binaryToBase64</em>(randomBytes);</pre><pre>  const<em> hasSetCredentials </em>=<em> await<br>    </em><strong><em>Keychain</em></strong><em>.setGenericPassword</em>(<em>ENCRYPTION_KEY</em>, randomBytesString);</pre><pre>  if<em> </em>(hasSetCredentials)<em> </em>{<br>    <em>return </em>{ <em>isFresh</em>:<em> true</em>,<em> key</em>:<em> </em>randomBytesString };<br>  }<br>};</pre><p>The most interesting bits here are the calls to Keychain to get an already existing password, and to set a new one if it doesn’t.</p><p>Before setting the new password though, we have to create it first. This is where two new function calls come in that we haven’t covered yet:</p><ul><li>generateSecureRandom: generates a secure random key of 32 bytes.</li><li>binaryToBase64: converts these bytes to a base64 string. This is our new, <a href="https://github.com/rh389/react-native-securerandom#react-native-securerandom">cryptographically-secure</a> password. 🎊</li></ul><p>The function getEncryptionKey then returns an object with two keys: isFresh and key. This is identical to the property that EncryptionGate passes on to the next component, the StoreGate. Let’s look at that next.</p><h4><strong>&lt;StoreGate /&gt;</strong></h4><p>This component has the following objectives:</p><ul><li>it takes an object and uses its key prop for encryption.</li><li>it generates the store using a generateStore function.</li><li>when it finishes, it passes the store and persistor into its children.</li></ul><p>We also include one extra check here:</p><p>If the key turns out to be fresh <em>and</em> there’s already data in our store, we have a problem: the data in our store can not be decrypted anymore, since a newly generated key won’t match the previous one.</p><pre><em>export </em>const<em> </em><strong><em>StoreGate</em></strong><em> </em>=<em> </em>({encryptionKey, children})<em> </em>=&gt;<em> </em>{<br>  const<em> </em>[<em>hasData</em>,<em> setHasData</em>]<em> </em>=<em> useState</em>(<em>false</em>);<br>  <br>  <em>useEffect</em>(()<em> </em>=&gt;<em> <br>    (async </em>()<em> </em>{<br>      <em>setHasData</em>(<em>await AsyncStorage.getItem</em>(storageKey));<br>    })(),<br>  []);</pre><pre>  //<em> hasData hasn&#39;t been set, so don&#39;t return anything<br>  </em>if<em> </em>(hasData<em> </em>===<em> false</em>)<em> </em>{<br>    <em>return null</em>;<br>  }</pre><pre>  //<em> if the encryption key is fresh, we need to flush AsyncStorage<br>  </em>if<em> </em>(<em>encryptionKey.isFresh </em>&amp;&amp;<em> </em>hasData<em> </em>!==<em> null</em>)<em> </em>{<br>    <em>clearStore</em>();<br>  }</pre><pre><em>  return children</em>(<strong><em>generateStore</em></strong>(encryptionKey,<em> </em>hasData));</pre><pre>};</pre><p>We need to take a closer look at generateStore() because that’s the place where the actual Redux store configuration takes place, including the encryption transform which makes all this magic possible ✨.</p><p>It’s very similar to what a configureStore() call does in many applications, only that it accepts and returns some additional parameters: encryptionKey, hasData go <em>in</em>.<em> </em>And an object with two props (store, persistor) comes <em>out</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fk8KVMIaeI1e3mmmRBL8pQ.jpeg" /><figcaption>The <strong>Store Gate</strong> and <strong>generateStore</strong> function at a glance</figcaption></figure><p><strong>Let’s take a look under the hood:</strong></p><pre><em>export </em>const<em> </em><strong><em>configureStore</em></strong><em> </em>=<em> </em>(<em>encryptionKey, hasData</em>) =&gt;<em> </em>{</pre><pre>  const<em> </em><strong><em>encryptionTransform</em></strong><em> </em>= <br>    <em>createEncryptor</em>({secretKey: encryptionKey});</pre><pre>  const<em> config </em>= {<br>    <em>key</em>:<em> </em>&#39;root&#39;,<br>    <em>storage</em>:<em> </em>AsyncStorage,<br>    <em>transforms</em>:<em> </em>[<strong>encryptionTransform</strong>],<br>  });</pre><pre>  const<em> persistedReducer </em>=<em> </em><strong><em>persistReducer</em></strong>(<em>config</em>,<em> </em>rootReducer);</pre><pre>  const<em> store </em>=<em> createStore</em>(<br>    <strong>persistedReducer</strong>,<br>    initialState<br>  );</pre><pre>  const<em> persistor </em>=<em> persistStore</em>(store);</pre><pre><em>  return </em>{ store, persistor };</pre><pre>};</pre><p>We’re setting up the encryption using the createEncryptor function from redux-persist-transform-encrypt and pass that into the transforms field of the config object. That’s the configuration we’ll use for the persisted reducer.</p><p>That persistedReducer gets passed into Redux’s createStore, and the resulting store gets passed back into the persistStore call of redux-persist.</p><p>The end result is a persisted store object that’ll automatically sync our reducer with the encrypted AsyncStorage, and a persistor object that allows us to run additional operations on the store, such as purge, flush or pause.</p><p>Sounds complicated? Let’s take a step back again and look at how all of this ties in to the overall component structure:</p><pre>&lt;<strong>EncryptionGate</strong>&gt;<br>  {(encryptionKey) =&gt; (<br>    &lt;<strong>StoreGate</strong> <em>encryptionKey</em>={encryptionKey}&gt;<br>      {(store, persistor) =&gt; (<br>        ...missing store logic goes here...<br>      )}<br>    &lt;/StoreGate&gt;<br>  )}<br>&lt;/EncryptionGate&gt;</pre><h4>Putting everything together</h4><p>We’re almost there. The last piece in our module is the actual context provider that wraps our store and makes it available to the rest of the app. Let’s take a look at the components we have so far and how everything fits together:</p><pre>&lt;EncryptionGate&gt;<br>  {(encryptionKey) =&gt; (<br>    &lt;StoreGate <em>encryptionKey</em>={encryptionKey}&gt;<br>      {(store, persistor) =&gt; (</pre><pre>        &lt;<strong>ReduxProvider</strong> <em>store</em>={store}&gt;<br>          &lt;PersistGate<br>            <em>persistor</em>={persistor}<br>            <em>loading</em>={null}<br>            <em>onBeforeLift</em>={<em>onBeforeLift</em>(store)}<br>          &gt;<br>            {children}<br>          &lt;/PersistGate&gt;<br>        &lt;/<strong>ReduxProvider</strong>&gt;</pre><pre>      )}<br>    &lt;/StoreGate&gt;<br>  )}<br>&lt;/EncryptionGate&gt;</pre><p>I usually call this file BootstrapPersistence to encapsulate all the store-related logic and then include it in the Bootstrap, App or index.js.</p><p>You may have noticed that there’s yet another new piece in our component cascade: PersistGate. It’s part of redux-persist and allows you to run additional code before lifting the curtains for the the rest of your app’s code. You may remember that this is where I took inspiration from for those other Gate components.</p><p>You can now wrap the rest of your app inside this scaffold and be confident that all your reducers are properly and securely persisted on the device.</p><h3>Aren’t we reinventing the wheel here?</h3><p>Of course, this kind of persistence is very specific to the kind of apps that require a very high level of security. And unless you’re working in a clinical environment, aviation or nuclear energy (anyone?), you may as well get away with much simpler solutions.</p><ul><li><a href="https://github.com/chaudhryjunaid/redux-persist-encrypted-async-storage/blob/master/index.js">redux-persist-encrypted-async-storage</a>: a simple encrypted wrapper around AsyncStorage without any Redux dependencies. Be aware though that it’s using uuidv4 which is slightly less secure than the library we’re using above, react-native-securerandom.</li><li><a href="https://github.com/oyyq99999/react-native-secure-storage#readme">react-native-secure-storage</a>: another wrapper for AsyncStorage which uses a native implementation of react-native-keychain as its primary storage mechanism, so you get some performance gains, but the amount of data you can store is limited to that of KeyStore/Keychain. This library also has a <a href="https://github.com/CodingZeal/redux-persist-sensitive-storage#readme">plugin for </a><a href="https://github.com/CodingZeal/redux-persist-sensitive-storage#readme">redux-persist</a>.</li><li><a href="https://docs.expo.io/versions/latest/sdk/securestore/">expo-secure-store</a>: the Expo-based version of an encrypted store, based on the same principles as react-native-secure-storage. As mentioned in there docs as well, size limit for a value is 2048 bytes.</li></ul><p>As you can see there are two limitations in those alternative libraries: you either don’t have a totally secure hashing algorithm (uuidv4 should be ok for most use cases though) or the amount of data you can store is limited.</p><p>I hope that explains why I came up with a slightly modified and unique way of encrypting data on the phone.</p><h3>What do you think?</h3><p>I’d be excited to hear how you’d use or modify this approach to fit your specific needs. Is it something you’d use in your project, does it achieve the goal of encrypting user data, or are there any loopholes I missed?</p><p>Remember, I’ve published the code in a public repository, so you can already go ahead and try it out without having to recreate any of the above yourself:</p><p><a href="https://github.com/marcelkalveram/react-native-bulletproof-redux-provider">marcelkalveram/react-native-bulletproof-redux-provider</a></p><p>Thanks for bearing with me until here and looking forward to hearing your feedback. 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3f7a2779f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-bullet-proof-approach-to-storing-sensitive-user-data-in-react-native-ab3f7a2779f9">A Bullet-Proof Approach to Storing Sensitive User Data in React Native</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How The Sustainable List came to life: journey of a side project]]></title>
            <link>https://marcelkalveram.medium.com/journey-of-a-side-project-how-the-sustainable-list-came-to-life-38cb3e11d86c?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/38cb3e11d86c</guid>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[fashion]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Thu, 28 May 2020 07:31:00 GMT</pubDate>
            <atom:updated>2020-05-28T11:41:24.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jxw4oBQ0O2rSiBlc" /><figcaption>Photo by <a href="https://unsplash.com/@guillaumedegermain?utm_source=medium&amp;utm_medium=referral">Guillaume de Germain</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I usually write about technical topics, but I want to use this opportunity to share the journey of a project I’ve been working on for the last year with my spouse and business partner <a href="https://medium.com/u/48d7345f4466">Andreea Apetrei Kalveram</a>.</p><h3>The elevator pitch 🔼 🔽</h3><p>In a nutshell, The Sustainable List is a curated list of sustainable fashion brands. Our goal is to help consumers navigate the ever-growing sustainable marketplace and give more visibility to brands that are socially and environmentally responsible.</p><p>Here’s the link to our website: <a href="https://thesustainablelist.com/">https://thesustainablelist.com/</a></p><p>Cool, still interested about how this project came to be? Please read on 👇</p><blockquote><strong>By the way, you can now go to our Product Hunt page <em>😻 </em>and join the discussion: </strong><a href="https://www.producthunt.com/posts/the-sustainable-list"><strong>https://www.producthunt.com/posts/the-sustainable-list</strong></a></blockquote><h3>When we got mad at the fashion industry 😡</h3><p>This story started a few years back, in 2016, when we got really mad at the fashion industry.</p><p>After watching the Netflix documentary <a href="https://truecostmovie.com/"><em>The True Cost</em></a><em>, </em>my wife and I felt seriously upset and concerned about the fashion industry’s negative impact on the planet’s environment and people. If you haven’t watched the movie yet, I can highly recommend it. It’s a look behind the scenes of the biggest players in the industry and how they produce their clothes. (Spoiler: you’ll be very disappointed by the dark side of humanity 😭)</p><p>While the ideas around <a href="https://www.theminimalists.com/minimalism/">Minimalism</a>, <a href="https://gregmckeown.com/book/">Essentialism</a> and <a href="http://stuffocation.org/">Stuffocation</a> weren’t entirely new to us, the movie definitely reinforced the idea of rethinking our behaviour as consumers, and we ended up buying less stuff while paying more attention to the purchasing decisions we made.</p><p>This change didn’t happen overnight, of course. And we’re aware how hard it is to make this transition, especially if the brands you want to support aren’t usually on your radar. It requires a lot of research and determination to resist quick and easy temptations and make responsible choices.</p><p>But the fashion industry is also currently the second biggest contributor to global warming (8–10% of global CO2 emissions), and we believe that sustainable fashion and responsible consumerism are the right path for safe-guarding the future.</p><h3>The right strategy for positive change 📈</h3><p>It’s impossible however to change peoples’ minds, let alone the colossal machinery that is the fashion business by throwing facts about global warming, deforestation or oppressive working conditions at them.</p><p>What I’ve learned over the last ten years though is that change is much more likely to happen if you provide an environment of inspiration rather than intimidation.</p><p>Let’s face it: people usually don’t want to be told how bad things are (even though I do 😂), but instead need positive examples of how much better life could be<em> </em>and how attainable these alternative solutions really are<em>.</em></p><p>Let’s see next how this way of thinking helped bring our idea to life…</p><h3>The incubation phase 🐣</h3><p>Since my wife had been a fashion enthusiast for a long time, it didn’t take too long for us to see realise there’s a growing trend of sustainability in the world of fashion.</p><p>However, we soon felt increasingly overwhelmed by the amount of brands in this space and couldn’t keep up with the quantity of information, like <em>where</em> a brand is from, <em>what</em> products they produce, or <em>how</em> they attain sustainability.</p><p>So we ended up creating a platform to help people navigate the marketplace, while hoping to give smaller, more independent brands more visibility to potential buyers. With this project, we want to do our bit to help people take more informed decisions and help reduce the negative impact we all have when it comes to buying new clothes. I hope that’s not too far-fetched 😊</p><p>Do you want to hear more now on how the project evolved, while I throw in some technical terms here and there? Here we go… 🤖</p><h3>Building a prototype 🏗</h3><p>Soon after coming up with the idea, we set up a cloud database on <a href="https://www.contentful.com/">Contentful</a> (a <em>headless</em> CMS) to start adding some brands with their corresponding certificates, categories and characteristics.</p><p>Since I’m familiar with the basics of data modelling, it took me an hour or two to set up the initial structure and walk my partner through the process.</p><p>That was the first step. And it allowed us to add the minimal amount of content to make the project even remotely interesting to anyone. But it also helped us figure out if we were on to something, or if we were missing anything critical.</p><p>To give an example: thanks to this practical approach of aggregating content, we had to wrap our head around some key questions, like how to categorise the brands we already had in our database and which certificates they had in common.</p><p>I have to say that in hindsight, I’m really happy about this <em>content-first</em> approach, because it also makes your life much easier when it comes to designing and implementing the user interface.</p><p>If you can already see and feel some real data while working on the initial prototypes, things just take shape more naturally, compared to when using dummy data or <em>lorem ipsum</em> placeholders.</p><p>Let’s take a look at the embarrassing first version of the page 🙈</p><figure><img alt="Screenshot of the first version of our the sustainable list" src="https://cdn-images-1.medium.com/max/1024/1*TNaHG08Cz2v49VrqJrIZnA.png" /><figcaption>The first version of The Sustainable List from May 2019</figcaption></figure><p>Ouch, that was painful! But as we all know:</p><blockquote><em>If You’re Not Embarrassed By The First Version Of Your Product, You’ve Launched Too Late.</em></blockquote><blockquote><strong><em>— </em>Reid Hoffman, founder of LinkedIn</strong></blockquote><p>And honestly, it did help us keep the motivation up and get some early feedback on the idea, such as making it a lot more visual and giving the page a nicer colour scheme, even though that may seem quite obvious as well.</p><p>The most important takeaway though was that people seemed to not be completely turned off by the idea, and encouraged us to keep going…</p><h3>The tech stack 🍔</h3><p>While we’re at it, let’s take a look at some of the tools and frameworks I’ve been using to put this together. If you’re not into web development and technology, you may as well skip this part.</p><p>So without further ado, let’s take a look under the hood:</p><ul><li><a href="https://create-react-app.dev/"><strong>React with Create React App</strong></a> ⚛️<br>This was the most easy choice for me since I’m using React in my everyday job. Even though many developers (including myself) always want to learn something new, I felt like bootstrapping in any other language or framework would have slowed us down a lot.</li><li><a href="https://evergreen.segment.com/"><strong>Evergreen UI</strong></a><strong> 🍃 <br></strong>Among the 1000 choices, I picked the first UI library I came across that felt was aligned with our needs. This one does provide some good looking design elements out of the box, but I found making things responsive a bit cumbersome over time, as I had to tweak and overwrite a lot of styles. In hindsights, I wish I had done some more research on this topic.</li><li><a href="https://reactjs.org/docs/hooks-intro.html"><strong>Hooks</strong></a><strong> 🎣<br></strong>In this project, I entirely dropped ES6 classes and built an app entirely with stateless functional components for the first time. I also decided not to use any state management framework (Redux/Mobx), and used the built-in useSelector and useDispatch hooks to manage state. While it took some time to get used to going more functional, it’s indeed easier to reason about, and I have now embraced this approach on other projects as well.</li><li><a href="https://nextjs.org/"><strong>Next.JS</strong></a><strong> and </strong><a href="https://vercel.com/"><strong>Zeit.now</strong></a><strong> (now Vercel) </strong>🚀<br>Here I actually did take a bit of a risk as I didn’t have any previous production-level experience with Next and Zeit. But <a href="https://codeburst.io/next-js-ssr-vs-create-react-app-csr-7452f71599f6">this article</a> convinced me of using an SSR-enabled boilerplate by default, or I’d have to wrap my head around this topic again, which I remember from a previous topic wasn’t always the most straight-forward. I don’t have any regrets so far. Next is really easy to learn and Zeit makes it incredibly simple to deploy your site to the public.</li><li><a href="https://www.contentful.com/"><strong>Contentful</strong></a> 📝<br>Adding content had to be really easy and intuitive, and my previous experience with this platform had been positive. Once you set up the model structure, you can define the appropriate formatting rules and validations for each field, so that an editor (in this case, my wife) can hardly make any mistake when putting in new content, which saves you from the hassle of integrating a lot of foolproof checks into your frontend.</li><li><a href="https://github.com/zeit/styled-jsx"><strong>styled-jsx</strong></a> 💅<br>I ended up using this styling library primarily because it comes with a <a href="https://github.com/zeit/styled-jsx">Next.js integration</a>. I wasn’t able to use styled-components, because it didn’t integrate well with Evergreen UI, nor did I want to use it because of some prior frustrations I had in a React Native project where styled-components led to a lot of unexpected overhead (which was probably my bad!) and testing issues.</li><li><a href="https://jaredpalmer.com/formik/"><strong>Formik</strong></a><strong> </strong>and<strong> </strong><a href="https://sendgrid.com/"><strong>sendgrid</strong></a><strong> 📩<br></strong>This almost goes without saying, but I just needed a simple, stupid implementation of transactional emails for our contact form, and those two tools made it really easy to implement (apart from the minor hassle of of setting up <a href="https://www.leighhalliday.com/secrets-env-vars-nextjs-now">secret API keys via Zeit.now</a> to make it more secure).</li><li><a href="https://mailchimp.com/"><strong>Mailchimp</strong></a><strong> 🦍<br></strong>Another no-brainer here, even though I have to admit I got a bit stuck with their API integration, and I feel like this is now more complicated than it used to be. So in the end I decided to go for their integrated pop-up solution which is as easy as pasting a line of JavaScript into your code which triggers an (almost) perfectly looking modal newsletter signup form.</li><li><a href="http://iubenda.com/"><strong>iubenda</strong></a><strong> 👩‍⚖️<br></strong>When you launch a product, you want to make sure you’re on the right side of the law. But cookie policies, GDPR, CCPA? 🤷‍♂️️ Unless you have a law degree, it seems like an insurmountable amount of rules to familiarise yourself with. Luckily, this tool makes it really easy to craft a “terms &amp; conditions” and “privacy policy” <em>without</em> being a lawyer, and makes integrating the necessary pieces of legal text into your page a piece of cake. This is one of those services which really make your life a ton easier.</li></ul><h3>Some iterations later 🔁</h3><p>Let’s now take a look at what the site looked like a year later, after implementing a (passable) colour scheme, figuring out a better layout for presenting those brands, and adding some more life to the whole thing by adding real photos wit real people in them.</p><figure><img alt="Screenshot of the current version of the sustainable list" src="https://cdn-images-1.medium.com/max/1024/1*mu56zFrQ_S95x1Q42hQbxA.png" /></figure><p>While I’m not a professional designer, I have to say I was quite happy with where we got with our scrappy bootstrapping approach, and how we took this initial idea from a raw database of brands to an actual website with very limited time and resources (I’ll talk about this in the takeaways).</p><p>Ok! After so much self-praise, let your criticism flow now! 🤐 But first, let’s see our CEO in action while he launches our little project on Product Hunt.</p><h3>The launch 🎬</h3><p>After a very intense year—mostly thanks to the little guy in the photo—we’re finally ready to launch our site (with all its imperfections). 🎉🥳🍾🎊</p><p>👉 <a href="https://www.producthunt.com/posts/the-sustainable-list">https://www.producthunt.com/posts/the-sustainable-list</a></p><p>Feel free to join the discussion and give us your feedback! We’re extremely excited to hear what you think and especially: what we can improve.</p><figure><img alt="Our son Noah looking at the Product Hunt website" src="https://cdn-images-1.medium.com/max/1024/1*YIL63L19WkU24YJBQ0dngg.jpeg" /><figcaption>Our CEO launching the site on Product Hunt 😸</figcaption></figure><h3>Key takeaways 🔑</h3><p>Now that we’re live (honestly, I still can’t content my excitement!) let me quickly sum up with some things I’ve learned along the journey.</p><h4>Avoiding “<em>featuritis”</em> 🤢</h4><p>Based on our experience in previous projects, we were trying to focus on the absolute core set of features.</p><p>Even though you can build a lot of interesting things around the topic of sustainability (ie. brand ratings, user reviews, sustainability guides, in-depth brand details) we decided to take the leanest approach possible. I’ll talk about some future enhancements in the final part of this blog post.</p><p>For now, the site offers a curated list of sustainable brands that you can search, sort and filter by the most common criteria. And that’s it.</p><p>Minimalism, FTW. 🇯🇵</p><h4>A very sustainable timeline 🐢</h4><p>A positive thing I noticed on this project (as opposed to most client projects I work on) is that there was never really a deadline for completion.</p><p>While this did result in a really slow pace, it was also the more sustainable approach, given that we not only had to juggle our full-time jobs, but also a one-year old son who usually doesn’t give a 💩 how busy we are.</p><p>My favourite strategy has always been to dedicate little chunks of time every day to something, even if it’s just 10 or 20 minutes. It’s a bit like a no-excuse/steady-progress way of getting things done. But it requires a high amount of consistency, because it’s very easy to let things slide when life gets in the way (which happens a lot with a little toddler 👶).</p><p>However, I also realised that when rushing through a project, an undesirable side effect is that good ideas and thoughts don’t have time to evolve and take shape. Due to the unpredictable nature of the brain, many good ideas often arise after you let a thought or idea settle for a few weeks, or even months: it’s like planting a seed and reaping the fruits, usually not on the next day.</p><h4>Do I actually use this? 🤪</h4><p>This was probably the most important question I asked myself while working on the project and after completing each task.</p><p>The good thing is: if you are an actual user of your own product, you can empathise, test and iterate much more efficiently than if you’re just vaguely interested in the value creation process. I’ve found that this leads to more intuitive problem solving and makes the process more enjoyable as well.</p><p>I’ve personally used The Sustainable List in several occasions. I’ve mainly used the filter mechanism to look for local brands, to keep the carbon footprint as low as possible. And I’ve discovered a lot of cool brands that I wasn’t aware of, but which I’m now a proud customer of.</p><p>Needless to say I feel in love with their products, but I’m also feeling better about the choices I made, supporting sustainable brands that work in a more responsible way (socially <em>and</em> environmentally).</p><h3>Our roadmap 🛣</h3><p>This has been our journey so far. There are a lot of potential features we want to work on in the future, but for the time being we’re also quite limited in terms of time and resources. So if anyone wants to jump in and lend a hand, please don’t hesitate to get in touch at <em>info (at) thesustainablelist.com</em>.</p><p><strong>Here are some of the improvements we may work on next:</strong></p><ul><li>User accounts: allow people to comment and rate brands</li><li>Guides: provide useful tips on sustainable fashion and living</li><li>Collections: feature a curated list of products, according to the season</li><li>Blog: provide regular insights into the sustainable fashion industry</li><li>Podcast: interviewing people from the world of sustainable fashion</li></ul><p>While we don’t have funding and aren’t planning to operate as a startup, we’d still appreciate if anyone interested in contributing to the project gets in touch with us to see if there are any opportunities for collaboration.</p><p>We believe that neither sustainability nor quality have to be sacrificed in order to make beautiful clothes, and that the future belongs to brands that have respect for the planet, its animals and its people 💚.</p><p>Please leave your feedback if you want to help us move this initiative forward, either here, on <a href="https://www.producthunt.com/posts/the-sustainable-list?utm_source=badge-featured&amp;utm_medium=badge&amp;utm_souce=badge-the-sustainable-list">Product Hunt</a> or via our <a href="https://thesustainablelist.com/contact">contact form</a>. You can also follow us on <a href="https://www.instagram.com/thesustainablelist/">Instagram</a> and <a href="https://www.facebook.com/thesustainablelist">Facebook</a>.</p><p>Thanks a lot for reading 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38cb3e11d86c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common cross-platform pitfalls to avoid in React Native]]></title>
            <link>https://javascript.plainenglish.io/common-pitfalls-i-run-into-on-every-react-native-project-7ea2e7c1d88?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea2e7c1d88</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Mon, 30 Dec 2019 06:32:56 GMT</pubDate>
            <atom:updated>2020-01-07T11:00:55.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GhaWmhwa-8vFHX9R" /><figcaption>Photo by <a href="https://unsplash.com/@art_maltsev?utm_source=medium&amp;utm_medium=referral">Artem Maltsev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Three things that people often get wrong when developing apps for iOS and Android</h4><p>One of the biggest troubles I often come across when building mobile apps in React Native isn’t necessarily technical: it’s that people design iOS apps for Android, or vice-versa.</p><p>Many companies choose React Native over native development because of its shallow learning curve. But what often falls by the sideway is that you’re still developing for two entirely different environments.</p><p>We should craft a user experience that follows each platform’s respective design guidelines.</p><p>For those unfamiliar with mobile, you should check out the <a href="https://material.io/design/">Material Design</a> guidelines for Android and the <a href="https://developer.apple.com/design/human-interface-guidelines/ios/overview/themes/">Human Interface Guidelines</a> for iOS. You don’t need to know them inside out, but it’s worth taking a look and familiarizing yourself with the core principles.</p><p>If you’re a React Native—or any kind of—mobile developer, you also often don’t have the leverage, authority or skills to actively shape the design process, so here are some questions you may want to throw at the designers in your team to make sure they’re concerned about the most critical platform differences:</p><ul><li>are we creating a flat or paper-based design?</li><li>do we stick to the default navigation behaviour, including transitions and gestures?</li><li>do we take into account how visual hierarchy is expressed differently on each platform?</li><li>what do icons and typography usually look like on iOS and Android?</li><li>how do form elements (radio buttons, switches) differ on each platform?</li></ul><p>For an exhaustive list of differences between iOS and Android, I can also recommend the following articles:</p><ul><li><a href="https://medium.com/@chunchuanlin/android-vs-ios-compare-20-ui-components-patterns-part-1-ad33c2418b45">Android VS. iOS: Compare 20 UI Components &amp; Patterns (Part 1)</a></li><li><a href="https://medium.com/@chunchuanlin/android-vs-ios-compare-20-ui-components-patterns-part-2-3edba2076b25">Android VS. iOS: Compare 20 UI Components &amp; Patterns (Part 2)</a></li></ul><p>With that in mind, let me walk you through some of the common pitfalls of cross-platform development that I run into on almost every React Native project.</p><h3>Navigation</h3><p>On Android, it’s more common than on iOS for the tab bar to sit at the top of the screen. Let’s take a look at the Facebook app as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mqweW_QuKYRjc_ifT4mxg.jpeg" /><figcaption>The Facebook app on iOS (left) and Android (right)</figcaption></figure><p>That’s on purpose because some apps don’t want you to accidentally tap on the native bottom bar on Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*x_4VB5mmSrEnHErdwppECg.png" /><figcaption>The native bottom bar on Android</figcaption></figure><p>Another important navigation-related detail is the header bar. On Android, its content is often left-aligned. Let’s take a look at the Twitter app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*49h3YswMlckNzCf42kPfug.png" /><figcaption>The navigation header bar on iOS (top) and Android (bottom)</figcaption></figure><p>Many mobile designers unfamiliar with Android consider this a bug and will tell you to fix it. But unless you have a strong reason to, it’s usually safe to stick to the default.</p><h3><strong>The Android back button</strong></h3><p>When adding custom screens like modals, bottom sheets, or any other custom screen that you can navigate to, most Android users will expect that they can discard it using the default Android back button.</p><p>Let’s take a look at the native bottom bar again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*VZhnyUg_bQOHBE-8MEY1tA.png" /><figcaption>The back button in the native Android bottom bar</figcaption></figure><p>I’ve seen React Native apps where tapping it would take you back to the previous route <em>underneath</em> the overlay or—even worse—quit the app!</p><p>Now, whenever you create a route that’s not hooked up to your navigation stack’s <em>default</em> behavior (usually provided by react-navigation) you have to know very well what you’re doing.</p><p>While it seems that you only have to add the missing <a href="https://facebook.github.io/react-native/docs/backhandler">BackHandler</a> to the new component, it may often entail a lot more work: since the screen won’t be added to the underlying navigation stack, it won’t show up in <strong>navigation history</strong> either, so a lot of unexpected things may happen as you go back and forth in your navigation stack and include custom routes this way.</p><p>You may actually want to familiarise yourself with <a href="https://reactnavigation.org/docs/en/custom-android-back-button-handling.html">custom Android back button handling</a> and how to <a href="https://reactnavigation.org/docs/en/custom-navigator-overview.html">build your own navigator</a> to get a deeper understanding of this topic.</p><h3>Safe areas</h3><p>Something that can be equally confusing—but this time on iOS—are the so-called safe areas.</p><p>Since the introduction of the iPhone X there are several areas on the screen where you should avoid putting any critical or interactive content. The reason is that these are reserved for native gestures, like swiping up from the bottom to switch between apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r1ITEfuJc3xtU_4zCJ8hw.jpeg" /><figcaption>Hardware constraints on iOS: safe areas on iPhone 11 (left) and iPad Pro (right)</figcaption></figure><p>It’s easy to avoid these by using SafeAreaView as a wrapper for <em>all</em> your screens (e.g. using a wrapper). But that also results in a poor user experience because the protected areas are now completely empty.</p><p>If you still want to leverage a shiny full-screen experience while making sure to not interfere with the phone’s native gestures (something that may lead to app store rejections, actually), you have to wrap your head around <a href="https://reactnavigation.org/docs/en/handling-iphonex.html">handling safe areas</a>.</p><p>I highly recommend you to get the hang of it as soon as possible in the process since dealing with it at a later point can result in a lot of painful refactoring.</p><p><strong>The Android display cut-out</strong></p><p>On top of that, you may have come across Android phones that share a similar layout peculiarity: the Android display cut-out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*ZWJUq9yDdNZEV0Ltl84lkA.jpeg" /><figcaption>The Anroid display cut-out on phones like the Pixel 3 XL</figcaption></figure><p>To deal with this particular issue, you actually need to go one level deeper and dig into the native layer. But before I go into any further here, let me point you to an <a href="https://dev.to/brunolemos/adding-notch-support-to-your-react-native-android-app-3ci3">article by Bruno Lemos</a> which does a very good job of explaining how...</p><h3>Design, design, design!</h3><p>Taking those things into account, you’ll already craft a much better native user experience on iOS or Android as a React Native developer.</p><p>But that doesn’t prevent us from the fact that we have to <em>think</em> in iOS or Android from the start, and not just throw an iOS design at Android, or the other way around.</p><p>The React Native ecosystem offers plenty of tools and libraries to design great user experiences for both platforms, but it is not a silver bullet solution that automatically transforms your design from one platform’s UI into another.</p><p><strong>Thanks a lot for reading! If you have any feedback regarding the cross-platform quirks mentioned above, feel free to drop a comment below, or get in touch with me via </strong><a href="https://twitter.com/marcelkalveram"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea2e7c1d88" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/common-pitfalls-i-run-into-on-every-react-native-project-7ea2e7c1d88">Common cross-platform pitfalls to avoid in React Native</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the gap from JavaScript to native user preferences in React Native]]></title>
            <link>https://javascript.plainenglish.io/bridging-the-gap-from-javascript-to-native-user-preferences-in-react-native-c7e03891a10f?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7e03891a10f</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 07:24:44 GMT</pubDate>
            <atom:updated>2019-09-26T08:14:53.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R-wwa1ztIHwce6Fw" /><figcaption>Photo by <a href="https://unsplash.com/@akovacsa?utm_source=medium&amp;utm_medium=referral">Andras Kovacs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lately, I’ve been working on integrating a GDPR opt-out feature into an app. This feature allows users to flip a switch to decide whether they want any privacy-related data to be tracked by our app or any of its third-party dependencies.</p><p>From a legal standpoint, that’s an interesting challenge, because if you could at any point use any of the tracked data to re-identify a person to which the data refers, it means that it has not been effectively anonymized, thus you’re not complying with the GDPR guidelines.</p><p>From a technical point of view, that means you have to completely disable any logic that may establish a connection to a third-party service sending user-specific information to a server, such as their IP Address, location, operating system, etc…</p><h3>Let’s narrow down the problem</h3><p>In our React Native project, we’ve been using some commonly used third-party libraries for tasks like analytics, logging and crash reporting. The bad news for developers is that most of these plugins have been developed way before GDPR came into existence.</p><p>And even though some of them provide a simple way to opt-out of their services through a method call in the JavaScript layer, others require you to dig into the native code and disable the plugin <em>before</em> it even gets initiated.</p><p>If you look at the setup instructions for any of those third-party tools, then usually they ask you to include a snipped of native code into your app. This snipped initializes the native library with which you’re then able to communicate from your JS code via the React Native bridge.</p><p>The question is: when a user opts out of GDPR from a part of the UI that’s written in JavaScript, how do we carry over that setting to the native layer, so that the next time the user starts the app, we can make sure it won’t load the third-party library any longer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlF4g_KKAMaJu8lPam7R6A.png" /><figcaption>The problem we’re facing: how do we carry over settings made in the JS layer to the native side?</figcaption></figure><h3>Native key-value stores in React Native</h3><p>React Native provides a Settings module out of the box. It allows us to read and write values from and to iOS’s <a href="https://developer.apple.com/documentation/foundation/nsuserdefaults">NSUserDefaults</a>. We can use this in our native code to read parameters that have been set in the JS layer. Nice! 😎</p><p>Unfortunately, there’s no equivalent for Android, so we need to use an open-source library to plug that gap. One of them is <a href="https://www.google.com/search?q=react-native-shared-preferences&amp;oq=react-native-shared-prefe&amp;aqs=chrome.0.35i39j69i57j0l4.3871j0j0&amp;sourceid=chrome&amp;ie=UTF-8">react-native-shared-preferences</a>. It serves as a wrapper around <a href="https://developer.android.com/reference/android/content/SharedPreferences">SharedPreferences</a>, the key-value store on Android. It lets us do (more or less) the exact same thing as the Settings API does for iOS.</p><h4>Abstracting it all away</h4><p>But there’s an even better library that I only stumbled upon after I had implemented a barebones solution, based on my initial findings. The library <a href="https://github.com/kevinresol/react-native-default-preference#readme">react-native-default-preference</a> is an abstraction for <em>both</em> platforms and lets us read and write data in a unified way to exchange information between JavaScript and native. Woohoo 🎉</p><p>Here’s an overview of the different key-value stores and which platforms they cover. On the left, you can see the two native libraries, on the right the one that comes with React Native out-of-the-box. At the bottom, I added the three solutions that help you cover both worlds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsTxdybNenCW4jcoEH1Trg.png" /><figcaption>An overview of key-value store solutions in React Native (left: native, right: JavaScript)</figcaption></figure><h4>The JavaScript implementation</h4><p>Equipped with this plugin, we can now go ahead and implement some simple logic to read and write data to the native layer, and which both—native and JavaScript—are able to read from.</p><pre>import <strong>DefaultPreference</strong> from &#39;react-native-default-preference&#39;<br><br>DefaultPreference.set(&#39;<strong>gdprOptOut</strong>&#39;, &#39;<em>yes</em>&#39;).then(() =&gt; ...)</pre><p>I’m getting/setting the value of the gdprOptOut parameter here, which I’ll later reuse in the native code examples. It’s a simple string (yes) that tells us whether the user has enabled privacy opt-out in our app. Note that it can’t be a boolean because every value has to be converted to a string first.</p><p>Another benefit of this plugin is that it makes the abstraction available in an async fashion by wrapping a Promise around the results from NSUserDefaults (which by default is synchronous).</p><h3>Accessing native key-value stores</h3><p>So far, so good! But how do we now access those variables on the native side? 🤷‍♂ 🤷‍♀</p><p>For those unfamiliar with native iOS and Android, this simple challenge can become a very daunting task, given that:</p><ul><li>you don’t know which libraries to import and where</li><li>you need to figure out where in your code to insert those statements</li><li>…and you have no idea how to write a conditional in Java or Objective-C</li></ul><h4><strong>Getting and setting preferences in iOS</strong></h4><p>In Objective-C, we can read values from a device’s user defaults by calling the standardUserDefaults method on the NSUserDefaults object. Then, we can extract the desired parameter using the objectForKey method on the returned defaults value.</p><pre>NSUserDefaults *defaults = [NSUserDefaults <strong>standardUserDefaults</strong>];<br>NSString *gdprOptOut = [defaults <strong>objectForKey</strong>:@&quot;gdprOptOut&quot;];</pre><p>It’s important to note that the return value of gdprOptOut is going to be a string as well, so the method call we’ll have to use for the subsequent conditional has to be isEqualToString:</p><pre>if ([gdprOptOut <strong>isEqualToString</strong>:@&quot;no&quot;]) {<br>  [PrivacyService initWith:API_KEY];<br>}</pre><p>In this case, when the parameter is <em>not</em> no(meaning that the user has not opted out of GDPR), we can safely initialize whatever service we’re going to use for tracking privacy data.</p><p><strong>Where to insert this code?</strong></p><p>In your AppDelegate.m you can now wrap your plugin’s initialization method with the conditional logic above. Usually, this can be found inside the didFinishLaunchingWithOptions method, which is responsible for all the setup logic of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*v30bMqmUuFvxuj8WpzLBfw.png" /><figcaption>Initialization logic for our privacy service in iOS’s <strong>AppDelegate.m</strong></figcaption></figure><p>I’ve added an additional statement here that sets the value to no if it hasn’t been set at all: if (!gdprOptOut) gdprOptOut = @&quot;no&quot;; (there’s probably a more elegant way to accomplish this in Objective-C 😊).</p><h4>Getting and setting preferences in Android</h4><p>To retrieve a result from the SharedPreferences key-value store in Java, you need to grab the whole key-value store like this:</p><pre>SharedPreferences settings = getApplicationContext().<strong>getSharedPreferences</strong>(&quot;KEY_VALUE_STORE_NAME&quot;, getApplicationContext().MODE_PRIVATE);</pre><p>There’s one additional parameter here you might not be aware of, the constant KEY_VALUE_STORE_NAME. This is the name of the store you’re working on.</p><p>If you’re using react-native-default-preference, the default name for this store is <strong>react-native</strong> (as defined in <a href="https://github.com/kevinresol/react-native-default-preference/blob/master/android/src/main/java/com/kevinresol/react_native_default_preference/RNDefaultPreferenceModule.java#L22">this file</a>). If you’re using react-native-shared-preferences , however, then the name is wit_player_shared_preferences by default 😕. That’s because the library author apparently built this library for a very specific purpose, but forgot to make the default name more generic. However, a <a href="https://github.com/sriraman/react-native-shared-preferences/pull/13">recent pull request</a> has made this configurable from outside as well.</p><blockquote>I’d recommend setting a store name in JavaScript all the time to avoid relying on those default values. You can use the setName method in either of the two plugins</blockquote><p>Now that we have access to the store, let’s see how we can read an actual value from it:</p><pre>String gdprOptOut = settings.<strong>getString</strong>(&quot;gdprOptOut&quot;, &quot;no&quot;);</pre><p>Oh, that was simple. If you’re wondering what the &quot;no&quot; bit means, that’s the default value in case it can’t find any stored item for the key you pass in.</p><p>Next, we want to run a simple comparison to decide whether we should initialize our privacy service. In Java, this is quite simple:</p><pre>if (<strong>gdprOptOut</strong>.equals(&quot;no&quot;)) {<br>  PrivacyService.init(this, API_KEY);<br>}</pre><p>Here, we’re just checking if the stored value is no (user has <em>not</em> opted out yet), so we’re safe to initialize whatever service is going to track the user’s data.</p><p><strong>Where to insert this code?</strong></p><p>In Java, the file where all the initialization logic goes is usually MainApplication.java. You can wrap your plugin’s initialization method (most likely inside of theonCreate method) with the conditional logic above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*3kFJFBg5QRuGy6tWuo_CZg.png" /><figcaption>Initialization logic for our privacy service in Android’s <strong>MainApplication.java</strong></figcaption></figure><h3>But there’s a caveat 😱</h3><p>Alright, we’ve managed to carry over the settings to the native iOS/Android code. But the native initialization logic only runs <em>once</em>, when the user opens the app and before the JavaScript kicks in.</p><p>What that means is that there’s basically no way to opt-out without <em>restarting</em> the entire app. Ouch! 🙇‍♂️ The solution for this (and I admit it’s not the most elegant one) is to ask the user to close and restart the app after opt-out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*6ssKicG7OJnc7yUeiYqnEA.png" /></figure><h3>Let’s recap</h3><p>You should now be equipped with the knowledge to read and write user preferences in the JavaScript application layer and be able to read those values from the native iOS and Android layer. If your use case requires to also write to the stores in <em>native</em>, check out the documentation of the two native libraries we discussed:</p><ul><li><a href="https://developer.android.com/reference/android/content/SharedPreferences">SharedPreferences</a> on Android</li><li><a href="https://developer.apple.com/documentation/foundation/nsuserdefaults">NSUserDefaults</a> on iOS</li></ul><p>The two libraries available in JavaScript are:</p><ul><li><a href="https://github.com/sriraman/react-native-shared-preferences">react-native-shared-preferences</a></li><li><a href="https://github.com/kevinresol/react-native-default-preference">react-native-default-preference</a></li></ul><p>I recently became a maintainer of the latter one, so if you have any suggestions on how to improve the library, please feel free to submit an <a href="https://github.com/kevinresol/react-native-default-preference/issues">issue</a> or submit a PR.</p><p>Hope you enjoyed this blog post. If you have any questions or comments, feel free to get in touch in the comments. Thanks a lot for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7e03891a10f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/bridging-the-gap-from-javascript-to-native-user-preferences-in-react-native-c7e03891a10f">Bridging the gap from JavaScript to native user preferences in React Native</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading React Native to version 0.59 and beyond: a step-by-step guide]]></title>
            <link>https://marcelkalveram.medium.com/upgrading-react-native-to-version-0-59-and-beyond-a-step-by-step-guide-d4c2926dd482?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4c2926dd482</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 10:33:36 GMT</pubDate>
            <atom:updated>2019-06-12T08:05:53.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RfOHbDM3hW9PEq5S" /><figcaption>Photo by <a href="https://unsplash.com/@sammgrdichian?utm_source=medium&amp;utm_medium=referral">Sam Mgrdichian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Upgrading is one of those tedious tasks that you’ll inevitably face at some point when working on a React Native project. If you’ve ever gone through this process, you’ve probably realised that it still has a lot of potential for improvement.</p><p>The most popular complaint about React Native, according to the recent <a href="https://github.com/react-native-community/discussions-and-proposals/issues/64">“What do you dislike about React Native?”</a> thread on GitHub is indeed: <strong>upgrading</strong>. It received 569 thumbs-up from the community, the second being <strong>Debugging</strong><em> </em>with<em> </em>350.</p><p>There’s been a very popular article on <a href="https://medium.com/react-native-training/updating-your-react-native-app-a724c996a76d">Upgrading React Native</a> about 2 years ago, when it was at version 0.45. Since React Native is now at 0.59 and a lot of things have happened in the meantime, I thought it might be a good moment to pick up the topic again and look at the current state of the upgrading process in detail.</p><h3>Why bother updating?</h3><p>There are a couple of reasons why you should update your React Native app on a regular basis. Some of the most compelling ones are:</p><ul><li>you’ll get all the latest performance improvements</li><li>you’ll have increased robustness and stability</li><li>you can access new APIs and features</li><li>you keep up with the latest breaking changes</li></ul><p>Having that in mind, let’s look at the different approaches to upgrading your app and its React Native-related dependencies.</p><h3>The different upgrade paths</h3><p>The recommended way to upgrade React Native according to <a href="https://facebook.github.io/react-native/docs/upgrading.html">its documentation</a> is the upgrade command which is included in the React Native CLI.</p><p><strong>Since version 0.59</strong> of React Native it’s based on the community plugin<a href="https://github.com/react-native-community/rn-diff-purge">rn-diff-purge</a> and basically runs a three-way merge based on the differences it finds between your current version of React Native and the one you’re upgrading to. If you’re on this version or above, use that and don’t bother reading the rest of this post.</p><p><strong>Before version 0.59 though</strong>, this process was more or less broken. People either used the outdated <a href="https://www.npmjs.com/package/react-native-git-upgrade">react-native-git-upgrade</a> or relied on a simple copy-and-replace mechanism provided by the CLI’s upgradecommand.</p><p>While the semi-automated copy-and-replace mechanism works well if you didn’t touch any of your project’s native code, you may run into issues if your project has reached a certain complexity, or if you simply haven’t updated in a while.</p><p>That said, rest assured that there are safer ways to upgrade your app. They might take a bit more manual work and careful code analysis, but usually won’t take you more of an hour or two, given that your update is not a major one with a lot of breaking changes and your version of React Native isn’t completely outdated.</p><p>I’ll cover them from simplest to hardest. You have to check which upgrade path applies to your particular situation:</p><ol><li><a href="#ecd8"><strong>Upgrading an app based on the Expo SDK (simple)</strong></a></li><li><a href="#9c8f"><strong>Upgrading apps <em>without</em> custom native code</strong></a></li><li><a href="#0ef6"><strong>Upgrading apps <em>with</em> custom native code (hard)</strong></a></li></ol><p>Before we get to the nitty-gritty, let me share some steps that all these paths have in common, so I don’t have to repeat myself below and you don’t end up reading the same thing twice.</p><h3><strong>Common steps before and after updating</strong></h3><p>What follows are some common steps you should always take <em>before</em> and <em>after</em> upgrading to a new version of React Native.</p><h4><strong>Before the upgrade process:</strong></h4><ol><li><strong>Check the changelog</strong> for everything that happened between the version you’re on and the version you’re upgrading to. Here are the three most important ones: <a href="https://github.com/react-native-community/releases/blob/master/CHANGELOG.md">React Native changelog</a>, <a href="https://github.com/facebook/react/blob/master/CHANGELOG.md">React changelog</a>, <a href="https://github.com/expo/expo/blob/master/CHANGELOG.md">Expo changelog</a>. The last one is only relevant if your app is based on Expo.</li><li><strong>Look at the third-party extensions</strong> you’re using (e.g. react-native-firebase) and check out their changelog as well to see if there are any incompatibility issues. Also check out the GitHub issues in case someone on a newer version has already reported a problem. If you have to update, watch out for any breaking changes or major version bumps.</li><li><strong>Isolate your upgrade</strong> properly to not interfere with your existing code or you may end up having some serious conflicts. I know this is trivial, but I find it important to stress as many people tend to hastily go through this process and then end up complaining why they can’t roll back. So, before anything, checkout a new branch: git checkout -b react-native-upgrade-vX.XX where X.XX is whatever version you’re upgrading to.</li></ol><h4><strong>After the upgrade process:</strong></h4><p>After upgrading, you might run into a ton of unexpected issues. Don’t be scared. Most of them can be resolved and are simply due to outdated caches or app files, incompatible dependencies or old settings. That’s why before you restart your app after an upgrade, make sure to always do the following:</p><ul><li><strong>Reset your simulator settings</strong>: If you’re running an iOS simulator, go to Hardware &gt; Erase all content and settings…</li><li><strong>Delete the app:</strong> by doing a long tap on the app icon and removing it from your phone or simulator (iOS) or running adb uninstall com.your-org.your-package(Android).</li><li><strong>Clear the native build folders:<br></strong>iOS: rm -rf ios/build<br>Android: ./android/gradlew clean -p ./android/</li></ul><p>Since a lot of the old version’s code might still be stuck in caches (metro bundler, watchman, node modules, build folders), you may also run the following command(s) to wipe out some of the caches and folders manually:</p><pre><strong>// delete watchman<br></strong>$ watchman watch-del-all</pre><pre><strong>// delete temporary files</strong><br>$ rm -rf $TMPDIR/react-*<br>$ rm -rf $TMPDIR/npm-*<br>$ rm -rf $TMPDIR/haste-*<br>$ rm -rf $TMPDIR/metro-*<br>$ rm -rf $TMPDIR/haste-map-react-native-packager-*</pre><pre><strong>// delete and reinstall node modules<br></strong>$ rm -rf node_modules &amp;&amp; npm install</pre><pre><strong>// delete and re-install CocoaPods, if any</strong><br>$ rm -rf ios/Pods<br>$ cd ios<br>$ pod cache clean --all</pre><pre><strong>// clean native build folders (as seen above)</strong><br>$ ./android/gradlew clean -p ./android/<br>$ rm -rf ios/build</pre><pre><strong>// clean iOS simulator files, replace &quot;appName&quot; with your own</strong><br>$ rm -rf ~/Library/Developer/Xcode/DerivedData/appName-*</pre><pre><strong>// reset React Native cache</strong><br>$ npm start -- --reset-cache</pre><p>I’ve created a gist that combines all of these commands into one: <a href="https://gist.github.com/marcelkalveram/0afe76b337edcd328a63b867ea610ba6">https://gist.github.com/marcelkalveram/0afe76b337edcd328a63b867ea610ba6</a>. <strong>Use this at your own risk! It’s quite aggressive and you should be 100% sure what you’re doing. Don’t say I didn’t warn you! ☝️</strong></p><p>Now that we’ve covered the basics, let’s dig into the actual upgrade process. Remember that depending on the state and type of app you’re running, there are three different paths, so make sure to read the heading and see which of the them applies to your specific use case.</p><p>Feel free to grab a cup of coffee before moving on… ☕️ Oh, and better schedule this task for a Monday morning instead of a Friday afternoon. 😜</p><h3>1. Upgrading an app based on the Expo SDK</h3><p>If you’re lucky enough to have built an app whose features are entirely covered by the Expo SDK, then updating can be done without too much hassle.</p><p>Expo provides a detailed walk-through for each update they’re releasing on <a href="https://blog.expo.io/">their blog</a>. You can find the one that corresponds to your version by googling for the one you’re targeting, e.g. “Expo update 32”, which will show <a href="https://blog.expo.io/expo-sdk-v32-0-0-is-now-available-6b78f92a6c52">this post</a> as the first result, or browse the <a href="https://blog.expo.io/">Exposition blog</a> directly.</p><p>I know this sounds kind of obvious, but I’ve spent about 15mins on this the first time I was looking for instructions on how to update Expo. 😊</p><h4>Minor note for people who’ve used create-react-native-app</h4><p>One thing that people tend to miss after updating Expo: if you’ve used <a href="https://github.com/react-community/create-react-native-app">create-react-native-app</a> to setup your repository, then all the scripts in package.json need to be changed from react-native-scripts to expo, e.g. react-native-scripts ios becomes expo start — ios. Expo CLI should issue a warning on this, but it’s still easy to miss.</p><h3>2. Upgrading apps without custom native code</h3><p>This upgrade path is for those people who’ve either ejected an existing Expo app or created their repository using react-native init and haven’t tweaked any of the native code so far. That means you’ve only touched the JavaScript files of the app and didn’t integrate any third-party plugins that contain native files (you didn’t use react-native link or manually link any extensions yet). Upgrading should be relatively straight-forward in this case.</p><blockquote><em>You should use this approach for any upgrade that targets version </em><strong><em>0.58 or before</em></strong><em>. From version </em><strong><em>0.59 forward</em></strong><em>, the automatic upgrade is based on</em><a href="https://github.com/react-native-community/rn-diff-purge"><em> rn-diff-purge</em></a><em> (see upgrade path three below) which will make the process easier in the future.</em></blockquote><p>Here are the steps that I usually follow to upgrade a React Native repository without any changes to the native code:</p><ol><li>Check your package.json</li><li>Update the React Native dependency to your new target, e.g.<br>&quot;react-native&quot;: &quot;0.58.0&quot;</li><li>Update all your third-party library dependencies as well. If any of these contain <strong>linked native code</strong> (ie. react-native-maps) you’ll need to use <a href="https://medium.com/p/d4c2926dd482/edit#0ef6">upgrade path three</a> as your repository will contain native code changes</li><li>Run npm install and take note of the React dependency, e.g. react-native@0.58.0 requires a peer of <strong>react@16.6.3</strong> but none is installed.</li><li>Update the React dependency to the new target as well, e.g. &quot;react&quot;: &quot;16.6.3&quot;</li><li>Run npm install again.</li><li>Now run react-native upgrade and it’ll walk you through the process of overwriting all the required file changes one by one. Apart from a few meta files, this should only affect the ios and android folders</li><li>Make sure to run the <a href="#99c7">post-upgrade steps</a> mentioned above to prevent any errors resulting from outdated caches</li></ol><p>This is the moment of truth: run react-native run-ios and react-native run-android to see if everything still works as expected.</p><p>If not, it’s not the end of the world. I’ve been there so many times and always found a way out thanks to the incredible support provided by the React Native community and the numerous GitHub and StackOverflow threads where people discuss and solve the most common issues.</p><h4>I see a “Could not find iPhone XXX simulator” error</h4><p>This is related to people running xCode 11 and later, which doesn’t seem to be compatible with previous versions of React Native CLI. Here’s a temporary fix: <a href="https://stackoverflow.com/questions/54504076/react-native-run-ios-returns-error-could-not-find-iphone-x-simulator">https://stackoverflow.com/questions/54504076/react-native-run-ios-returns-error-could-not-find-iphone-x-simulator</a></p><h3>3. Upgrading apps with custom native code</h3><p>If your app has already reached a certain point of complexity and code changes in the native realm (you <em>have</em> used react-native link or did some manual linking of third-party extensions), there are two scenarios:</p><ul><li><strong>you’re on version 0.59+</strong> of React Native and can run the new upgrade command using react-native upgrade which is based on rn-diff-purge and should run an automatic three-way merge. If everything goes well, you’ll end up with no conflicts. If any of the diffs result in a conflict, you’ll have to resolve them manually and commit the changes.</li><li><strong>you’re on version 0.58 or before</strong> of React Native which means the react-native upgrade command is not reliable and you should do the update manually and in incremental steps as described below.</li></ul><blockquote><em>There’s also the possibility to install the new upgrade command in versions </em>lower<em> than 0.59 as described </em><a href="https://github.com/react-native-community/cli/blob/master/docs/commands.md#upgrade"><em>here</em></a><em>: “If you’d like to upgrade using this method from React Native version lower than 0.59.0, you may use a standalone version of this CLI: </em><em>npx @react-native-community/cli upgrade.”</em></blockquote><p>Let’s continue for those of you who are on version 0.58 or lower and want to upgrade to React Native 0.59 or higher. This is by far the most risky and fragile update path, so a lot of care needs to be taken while going through the different steps.</p><p>Updating this way requires you to bump your React Native version from the version you’re currently on to the target version one by one, using the table from the <a href="https://github.com/react-native-community/rn-diff-purge#diff-table-full-table-here">rn-diff-purge</a> repository. Like this, you don’t risk breaking any of the native code and can analyse/debug the changes carefully and won’t end up with a big pile of diff commits that you throw at your application.</p><p>But let’s tackle them one by one:</p><blockquote><em>FYI: steps 1–6 are exactly the same as in </em><a href="#9c8f"><em>upgrade path two</em></a></blockquote><ol><li>Check your package.json</li><li>Update the React Native dependency to your new target, e.g.<br>&quot;react-native&quot;: &quot;0.58.0&quot;</li><li>Update all your third-party library dependencies as well. If any of these contain <strong>linked native code</strong> (ie. react-native-maps) and you’re using CocoaPods, you might have to upgrade your Podfile as well. Refer to the dependency’s changelog and install instructions for more detail. In any case, we’re going to reinstall all pods as well after we’re done</li><li>Run npm install and take note of the React dependency, e.g. react-native@0.58.0 requires a peer of <strong>react@16.6.3</strong> but none is installed.</li><li>Update the React dependency to the new target as well, e.g. &quot;react&quot;: &quot;16.6.3&quot;</li><li>Run npm install again</li><li>Using <a href="https://react-native-community.github.io/rn-diff-purge/">this table</a>, check the differences in code between your origin and target version and check if it’s feasible to apply them all at once. If not, consider upgrading in smaller, incremental steps, e.g. from version 0.56 to 0.57 before doing a major leap from 0.56 to 0.57.8.</li><li>Run cd ios &amp;&amp; pod repo update &amp;&amp; pod install to reinstall any existing CocoaPods dependencies.</li></ol><p>Run react-native run-ios and react-native run-android to see if everything is working fine.</p><p>That’s it, almost. Usually, the hard part of upgrading React Native starts after you’ve upgraded your files and is about ironing out all the issues that you run into.</p><p>In the unlikely case that everything went perfectly smooth, congratulate yourself and test your app thoroughly before opening that bottle of champagne. 😉</p><p>It’s more likely though that there’ll be some glitches you need to take care. We’ll cover some of these in the following, last section of this blog post.</p><h3><strong>Common pitfalls</strong></h3><p>While it’s impossible to cover all the issues you might run into, I thought it might be useful to cover the most common ones that I’ve seen.</p><h4><strong>Upgrading to React Native 0.56</strong></h4><p>With this upgrade, you’ll probably run into issues related to the Babel 7 update. Check out <a href="https://github.com/react-native-community/releases/blob/master/CHANGELOG.md#updating-to-this-version">this part</a> of the changelog for instructions on how to upgrade your JavaScript configuration.</p><p>Basically, you have to make sure that you have installed the new Babel preset:</p><pre>npm install -D metro-react-native-babel-preset</pre><p>… and babel.config.js is configured accordingly to make use of it:</p><pre>module.exports = {<br>  presets: [&quot;module:metro-react-native-babel-preset&quot;]<br>}</pre><p>Since this version introduces the new project-wide babel.config.js file, you can also consider deleting .babelrc. More on this in the <a href="https://babeljs.io/docs/en/next/config-files#configuration-file-types">Babel docs</a>.</p><h4><strong>Upgrading to React Native 0.57</strong></h4><p>When you upgrade to this version you need to upgrade react and react-test-renderer to version “16.6.3”, as stated in the release notes.</p><p>If you run into any xCode 10-related issues, check out <a href="https://github.com/react-native-community/releases/blob/master/CHANGELOG.md#known-issues-1">this part</a> of the changelog for instructions on how to fix them. Version 0.58 includes those fixes as well, so you might consider upgrading to that directly.</p><p>The following GitHub repo may help as well as it documents the most common errors when upgrading to 0.57.</p><p><a href="https://github.com/tylergaw/RNUpgradePath">tylergaw/RNUpgradePath</a></p><h4><strong>Upgrading to React Native 0.58</strong></h4><p>Before upgrading to this version, check out the <a href="https://github.com/react-native-community/releases/blob/master/CHANGELOG.md#breaking-changes-">breaking changes</a>.</p><p>As stated in the release notes, there are two important changes on each platform:</p><ul><li>for iOS: you’ll need to manually link JavaScriptCore.framework when upgrading; this can be done via Xcode, and following the steps shown <a href="https://camo.githubusercontent.com/c09cd42747364b498efa7c82fcb73978ba076eae/687474703a2f2f646f63732e6f6e656d6f62696c6573646b2e616f6c2e636f6d2f696f732d61642d73646b2f616464696e672d6672616d65776f726b732e706e67">here</a>.</li><li>for Android: it is possible that you’ll face an AAPT error regarding missing resources. In this case, you should try to update the build tools versions to buildToolsVersion = “28.0.2” in your android/build.gradle file.</li></ul><h4><strong>Upgrading to React Native 0.59</strong></h4><p>This releases includes an upgrade of the CLI’s upgrade command, which will hopefully make this blog post obsolete soon. 😄</p><p>If you get any runtime crashes on Android, check out the release notes section on <a href="http://facebook.github.io/react-native/blog/2019/03/12/releasing-react-native-059#breaking-changes">breaking changes</a>, or look at the <a href="http://facebook.github.io/react-native/blog/2019/03/12/releasing-react-native-059">full release notes</a>.</p><h4>Upgrading to React Native 0.60</h4><p>This is the latest version and should be used with care, as it’s still just a release candidate. A changelog isn’t available yet, but you can follow <a href="https://github.com/react-native-community/releases/issues/116">this thread</a> to get updates on the state of this version.</p><h3>Help me improve this article</h3><p>If you think I missed anything essential or run into an issue that I haven’t documented and you think should be included in this article, please let me know.</p><p>Thanks for reading and I appreciate your comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4c2926dd482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anti-patterns to avoid when building a component library in React Native]]></title>
            <link>https://levelup.gitconnected.com/anti-patterns-to-avoid-when-building-a-component-library-in-react-native-61f11d8c9797?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/61f11d8c9797</guid>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 06:00:12 GMT</pubDate>
            <atom:updated>2019-07-16T08:31:12.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8VMLKs-jIIAOKzj" /><figcaption>Photo by <a href="https://unsplash.com/@marcello54?utm_source=medium&amp;utm_medium=referral">Marcello Gennari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I’ve helped a client migrate their e-commerce front-end from a native wrapper app to React Native.</p><p>Since a big part of the team didn’t have any previous experience with React, it was natural that we’d run into a lot of inconsistencies in the beginning. My job was to help iron these out and lay the groundwork for a more maintainable codebase.</p><p>One of the challenges was to understand and organise the building blocks of the UI layer. I realised quickly that when working with a team of 5+ people in React, it’s very common to end up with a big, fragmented collection of UI components.</p><p>That’s why one of the initial efforts of our collaboration was to set up some guidelines for a UI library that would be understandable, maintainable, extensible , reusable and testable. (did I forget any -able?)</p><p><strong>The below techniques are by no means revolutionary. Most teams that work on bigger-scale projects are most likely familiar with the concepts of reusable components, decoupling and universal themes. If that’s the case, you may go directly to the section “</strong><a href="#a8ee"><strong>Complementary building blocks</strong></a><strong>” at the very end of this post or just skip it entirely.</strong></p><p>To get started, let‘s take a look at the anti-patterns I spotted as we ventured out into the unknown and started writing our first components.</p><h3>Anti-pattern #1: decreasing component reusability</h3><p>It’s all too common to arbitrarily prefix components to give them more meaning, emphasise in which context they’re being used, or simply increase their specificity.</p><p>Typical examples are when people use component names like LoginButton, RegisterLink or—even worse—FilterHeaderRightMenuCloseButtonIcon.</p><p>There are two kind of problems here that I want to point out.</p><p><strong>Firstly</strong>, any style definitions inside FilterHeaderRightMenuCloseButtonIcon that you may want to reuse elsewhere are now pretty much locked up in there:</p><ul><li>trying to import them from this component would introduce coupling in a way that nobody is ever going to forgive you for</li><li>repeating them would lead to code duplication, something they teach you at primary school is a bad practice</li></ul><p><strong>Secondly</strong>,<strong> </strong>FilterHeaderRightMenuCloseButtonIcon tells me a lot more about the context it’s being used in than what it <em>does</em>. Since its purpose is to display an Icon, the FilterHeaderRightMenuCloseButton prefix is probably redundant.</p><p>Sure, prefixing and isolating components like this makes your job easier in the short term. You write a component with a specific name, so it won’t clash with any other, and the styles are exactly as your designer has specified. Pixel-perfection and zero bugs… who wouldn’t want that? 🤷‍♂️</p><p>The problem starts when your app grows in size, and structure, semantics and naming become more relevant.</p><p>From my experience, hinting at what a component <em>does</em> (e.g.: ScrollContainer) rather than where it appears (e.g.: InnerWrapper) in a tree of many nodes can make a big difference when other people have to read your code, and will save you from going through a lot of refactoring headaches in the future.</p><p><strong>Say hi to purpose-revealing, configurable UI components</strong></p><p>That’s why I usually find it more valuable to write components that</p><ul><li>have less verbose names, e.g. Icon instead of CloseButtonIcon</li><li>are named according to their purpose, e.g. ScrollContainer vs. InnerWrapper</li><li>are configurable through props, e.g. &lt;Icon type=&quot;close&quot; /&gt;</li></ul><p>Of course, there’s a fine line between writing a component that accepts all kinds of properties: &lt;Button right big leftAlign underline smallText /&gt; and concise components that do <em>just enough</em>. 🎯</p><h3>Anti-pattern #2: cross-references, the enemy of decoupling</h3><p>Another thing that I’ve observed a lot is when people create cross-references between unrelated files and folders.</p><p>When referencing files within a coherent entity, such as a particular screen or a more complex component, that’s acceptable because they are still one self-contained unit whose parts aren’t applicable anywhere else.</p><p>Where it does get messy is when you reference some part of your code (like a style definition or a sub-component) from a completely unrelated file. A good indicator for this kind of code smell 👃 is when someone imports a file from a folder that can only be accessed when jumping a few levels higher in the component hierarchy.</p><pre><em>// icon.jsx</em><br>import { <strong>letMeJustGrabThis</strong> } from &quot;../../../../../../components/button&quot;</pre><p>I think even without being a guru programmer, you’ll realise that this way of coupling can become a bit of a nightmare to maintain 😱:</p><ul><li>If any of these dependencies disappears, your’s will go down with it.</li><li>None of the components will be testable as independent entities, as you’ll have to either mock the imported module, or blindly rely on its correct behaviour</li><li>The cognitive load to understand your component is getting bigger, making it much harder to refactor over time</li></ul><p><strong>Decoupling (and unit testing) to the rescue!</strong></p><p>But how do we achieve this? To be confident that your component is a self-contained entity, it ideally shouldn’t rely on cross-references to any other components.</p><p>I’ve found unit testing to be really efficient to reveal those interdependencies. Since it requires you to test and configure your component in complete isolation, it forces you to rethink and reconsider the dependencies it pulls in. Let’s look at a simple example in Jest.</p><pre>// component.test.jsx<br>import { <strong>ComponentOne</strong> } from &quot;../ComponentOne&quot;</pre><pre>it(&quot;should behave in a certain way&quot;, () =&gt; {<br>  const result = <strong>ComponentOne</strong>.doSomething();<br>  expect(result).toBe(&quot;expectedResult&quot;);<br>}</pre><p>If this would require you to mock out several other components that ComponentOne depends upon, or you’d have to turn it into an instantiable object and pass in dozens of modules via dependency injection to make it work, chances are your component is tightly coupled with other pieces of software you’re writing.</p><p>Not that this is a bad thing per se, but something to keep an eye on before your app turns into an unmanageable, monolithic beast. 🦍</p><h3>Anti-pattern #3: inconsistency</h3><p>More often than not, people end up writing stuff like this, either out of ignorance or sheer laziness.</p><pre><em>// </em>👨‍💻 <em>writes screenOne/componentOne.jsx</em><br>const <strong>ComponentOne</strong> = props =&gt; &lt;a style={{ padding: <strong>12</strong>, ... }} /&gt;</pre><pre>// 👩🏻‍💻 <em>writes screenTwo/componentTwo.jsx<br></em>const <strong>ComponentTwo </strong>= props =&gt; &lt;a style={{ padding: <strong>12</strong>, ... }} /&gt;</pre><p>For the web, this issue was quite common in the pre-preprocesser age when variables didn’t exist in CSS. Thanks to tools like SASS and LESS, we were relieved from the pain of repeating the same style definitions over and over again, and were able to pull in common parameters from a global theme.</p><p>With React however, it feels like we need to relearn some of these techniques as we’re now thinking in terms of <em>components</em>. As a result, our style definitions are often scattered across many, independent units. That makes it so much easier to repeat ourselves, compared to when we were writing stylesheets and using classes to share reusable properties for things like spacing, font sizes, colours etc...</p><p>Especially when working with many people on a team, it’s very easy to be unaware of the style definitions other people have written, and end up repeating those values that should be shared across components.</p><p>Of course, that’s a missed opportunity not only to save yourself some work, but also to bring some consistency into your design<strong>.</strong> Who doesn’t appreciate a universal set of spacing, font and colour definitions that can be applied throughout the whole app? <em>🎨</em></p><p>In React, these usually go into a shared theme folder that resides at the root of the app from which every component can import.</p><pre><em>/theme/index.js</em><br>export const <strong>spacing</strong> = 12</pre><p>Then your component can use them as follows:</p><pre><em>/screenOne/componentOne &amp;&amp; /screenTwo/componentTwo<br></em>import { <strong>spacing </strong>} from &#39;~/theme&#39;</pre><pre>const Container = props =&gt; <br>  &lt;a style={{ padding: <strong>spacing</strong>, ... }} /&gt;<br>}</pre><blockquote>If you work with a library like <strong>Styled Components</strong>, you may consider using a <a href="https://www.styled-components.com/docs/advanced">ThemeProvider</a> which makes those universal values available across your whole app. In this case, you pass all the styles into that higher order component.</blockquote><p>As your theme grows in size, you may consider splitting it up into multiple files (e.g. spacing, typography, colors, etc.):</p><pre>/theme/spacing.js<br>/theme/color.js<br>/theme/typography.js</pre><p>…and then export all of them from the root of the theme folder’s index file:</p><pre><strong><em>// /theme/index.js</em></strong><br>export * from &quot;./color&quot;<br>export * from &quot;./spacing&quot;<br>export * from &quot;./typography&quot;</pre><p>Also, importing them is way easier when using a <a href="https://github.com/tleunen/babel-plugin-module-resolver">module resolver</a> instead of writing out those long path names all the time.</p><pre><em>// this short form...</em><br>import { <strong>spacing</strong> } from &quot;~/theme&quot;</pre><pre><em>// looks much nicer than:</em><br>import { <strong>spacing</strong> } from &quot;../../../../../theme&quot;</pre><h3>Complementary building blocks</h3><p>If all of this is familiar to you, there are some additional building blocks that from my experience can help your team become more consistent, increase code quality and build a more reusable component library:</p><ul><li><strong>A style guide</strong>: when your app’s design is backed by a clean and well-maintained style guide that describes each component in detail, developers will have a much easier job at identifying components that are reusable across screens, and how they should be made configurable. <a href="https://storybook.js.org/">Storybook</a> can help you further streamline this process, and pave the way towards a well-maintained and tested component library in React.</li><li><strong>Review process</strong>: when people peer-review each other’s code, it’s much easier to spot issues that violate the above-mentioned principles. A proper pull request process (ideally with at least 2 reviewers per feature) usually helps eliminate a significant amount of inconsistencies and bugs</li><li><strong>Continuous integration</strong>: on most bigger projects, developers set up a deployment pipeline to help automate repetitive tasks. If you’re in the lucky position to have a continuous integration process, you should automate things like unit, integration and regression testing, and potentially include a tool like <a href="https://codeclimate.com/">Code Climate</a> that can help identify some of the inconsistencies or duplications in your codebase automatically.</li></ul><p>That’s it! Hope you enjoyed this post. Please feel free to share your experience with building reusable component libraries, or drop a question if anything in this post has been unclear. Thanks a lot for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61f11d8c9797" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/anti-patterns-to-avoid-when-building-a-component-library-in-react-native-61f11d8c9797">Anti-patterns to avoid when building a component library in React Native</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The intricacies of nesting navigators in React Native using react-navigation]]></title>
            <link>https://itnext.io/the-intricacies-of-nesting-navigators-in-react-native-using-react-navigation-fef52ca72964?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fef52ca72964</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 07:01:00 GMT</pubDate>
            <atom:updated>2018-12-05T10:07:57.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fHSUkLSz6Dw_ugee" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>This is the last post in a 4-part series about building the iOS and Android app for </strong><a href="https://uncovercity.com/"><strong>uncovercity</strong></a><strong> using React Native. You can find the other ones here:</strong></p><ol><li><a href="https://itnext.io/speeding-up-the-build-of-a-surprise-dinner-app-in-react-native-using-expo-2c18beabaaa7">Speeding up the build of a surprise dinner app in React Native using Expo</a></li><li><a href="https://itnext.io/battle-testing-a-ride-sharing-api-and-react-natives-mapview-in-expo-c0ce5d50cbf0?source=your_stories_page---------------------------">Battle testing a ridesharing API and React Native’s MapView in Expo</a></li><li><a href="https://medium.com/@marcelkalveram/supporting-multiple-languages-in-react-native-with-expos-localization-module-9611f9e3b6a0">Supporting multiple languages in React Native with Expo Localization</a></li><li>The intricacies of nesting navigators in React Native using react-navigation</li></ol><p>In one of my most recent projects, I built the native app for Spanish startup <a href="https://uncovercity.com/">uncovercity</a> using React Native.</p><p>One of the most interesting challenges I faced was setting up the navigational structure based on a set of Invision designs. In this post, I’m going to talk about them in detail and walk you through the solutions I came up with.</p><h3>It all starts with a tree</h3><p>The following bullet points illustrate how the app was structured. I’m already giving you a little hint on which type of navigator I used for each element that contains child routes.</p><pre>- Main <strong>(StackNavigator)</strong><br>  - Home<br>  - Login<br>  - Recover password<br>  - Sidebar <strong>(DrawerNavigator)</strong><br>    - Router <strong>(StackNavigator)</strong><br>      - Experience<br>      - Experience Map<br>      - Experience Active<br>      - Experience Active Detail<br>      - Map<br>      - Evaluation<br>    - PastExperiences<br>    - FAQ<br>    - Contact</pre><p>Let me walk you through this tree step by step.</p><h4>Level 1: Stack Navigator — the welcome and login screen</h4><p>As you can see, the root element is a <strong>StackNavigator</strong>. Since the first three screens (Home, Login, Recover password) just show up on top of each other as you move from one to the next, we can use a simple StackNavigator which comes with a nice default transition (slide-to-left on iOS, slide-to-top on Android).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*iftff5iPBn7ioKAU_phrtw.gif" /><figcaption>The Stack Navigator in action</figcaption></figure><h4>Level 2: Drawer Navigator — the sidebar</h4><p>The next component serves as a container for a bunch of other routes. We’re using <strong>DrawerNavigator</strong> here so that the user can slide in a sidebar menu from the left using touch gestures or the controversial hamburger icon in the top left corner of the screen.</p><p>From the sidebar, the user can get quick access to some static pages like FAQ and Contact. But by default, it displays another container element which contains a couple of other sub-routes, the <strong>Router</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*Q_YC9FUU9pNGxzm22X9faQ.gif" /><figcaption>The Drawer Navigator in action</figcaption></figure><h4>Level 3: Stack Navigator — the router</h4><p>The router is the heart of the app and contains most of the content. It’s where the user can see the current status of her (dinner) experience, a screen with detailed info about the venue, a map with the pickup/return point and an evaluation screen that lets her rate the experience when it’s over.</p><p>This again is a <strong>StackNavigator</strong> because we want to use the default transition on iOS and Android. But the router also contains some additional startup logic that I’ll cover in more detail below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*apa-PiYw_qec1NxLwmMeLQ.gif" /><figcaption>The nested Stack Navigator in action</figcaption></figure><h3>Challenges I faced using react-navigation</h3><p><a href="https://reactnavigation.org/">React Navigation</a> simplifies a lot of things that are hard to achieve in native iOS and Android. But it also comes with its own set of issues whose solution or workaround is not always straightforward.</p><p>What follows are the different issues I ran into and how I solved them.</p><h4>Challenge #1: enabling header bars inside a DrawerNavigator</h4><p>The StackNavigator has a header bar which is enabled by default. It can be disabled using headerMode: none on the StackNavigator’s <a href="https://reactnavigation.org/docs/en/stack-navigator.html#stacknavigatorconfig">visual options</a>. This is desirable when you want the current screen to cover the entire viewport, including the space that the header usually occupies.</p><p>What’s not so intuitive is when you’re inside a DrawerNavigator and want to enable the header bar for all its children. The DrawerNavigator doesn’t provide an inheritable headerMode option like StackNavigator since its purpose is not to give you a navigable stack of screens, but a flat hierarchy that contains screens with no header by default.</p><p>To enable the header bar for those screens as well, you need to wrap each of them in an additional StackNavigator. This brings back the header bar for each of its child screens, even though we only have one and actually abuse the StackNavigator for this simple purpose. While this seems like a hack, it still seems to be the <a href="https://github.com/react-navigation/react-navigation/issues/1632#issuecomment-305291994">most common </a>workaround in most situations.</p><pre>const One = <strong>StackNavigator</strong>(<br>  {<br>    main: { screen: Main } // only has one route<br>  },<br>  {<br>    navigationOptions: {<br>      <strong>headerMode: &#39;screen&#39;</strong> // enabling header mode for main screen<br>    }<br>  }<br>);</pre><pre>const AppNavigator = <strong>DrawerNavigator</strong>({<br>  one: { screen: One },<br>  two: { screen: Two }<br>});</pre><h4>Challenge #2: toggling the sidebar from within nested routes</h4><p>Next, I was wondering how to toggle the DrawerNavigator’s sidebar from a component inside a nested route.</p><p>Since React Navigation’s 2.0 update you can use the openDrawer function on the navigation property. But that property isn’t available in each component unless you pass it down as a prop, which sometimes means passing it down a long component chain.</p><p>A neater solution (spotted in <a href="https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html">react-navigation’s documentation</a>) is to store the DrawerNavigator’s reference in a service and importing it wherever you need access to the openDrawer function. This is what the service’s methods do:</p><pre>function <strong>setTopLevelNavigator</strong>(navigatorRef) {<br>  _navigator = navigatorRef;<br>}</pre><pre>function <strong>openDrawer</strong>(routeName, params){<br>  _navigator.dispatch(DrawerActions.openDrawer());<br>}</pre><p>The component that renders the DrawerNavigator then has to pass the navigator reference to the setTopLevelNavigator function.</p><pre>&lt;TopLevelNavigator<br>  ref={<strong>navigatorRef</strong> =&gt; {<strong><br> </strong>   NavigationService.setTopLevelNavigator(<strong>navigatorRef</strong>);<br>  }}<br>/&gt;</pre><p>Now you can simply call the navigate function from anywhere to have access to the DrawerNavigator &#39;s openDrawer method:</p><pre>NavigationService.<strong>openDrawer</strong>();</pre><blockquote>You could probably accomplish the same using React’s Context API (introduced in React 16.3) or using Redux or Mobx, but at the time of writing this code, this seemed to be the most simple solution without introducing any overhead.</blockquote><h4>Challenge #3: taking authenticated users to the user area</h4><p>If you’re a registered user and have already logged into the app before, you obviously want to be treated as a logged-in user the next time you come back.</p><p>Coming back to the navigation tree outlined above, that would mean taking her from the root navigator (Main) to one of the screens nested inside the Router stack. Quite a leap!</p><pre><strong>Main</strong> <strong>-&gt;</strong> Sidebar <strong>-&gt;</strong> Router <strong>-&gt;</strong> <strong>Experience<br>     -&gt; Login</strong></pre><p>In <strong>Main</strong>, we grab the users current status from the phone’s local storage (AsyncStorage). If the user <em>is</em> logged, it will contain an object with the user’s details (ID, email, name) and we take her to the next level, <strong>Sidebar.</strong> If she is <em>not </em>logged in, she’ll be taken to the <strong>Login</strong> screen instead.</p><pre>const user = await <strong>AsyncStorage</strong>.getItem(&#39;user&#39;);</pre><p>Since it’s an async function, we need to wait for it to complete before rendering the outer navigator, so we return a loading screen in our render function and we only set loading to true once our AsyncStorage operation has completed.</p><pre>if (this.state.loading) {<br>  return &lt;<strong>LoadingScreen</strong> /&gt;;<br>}</pre><p>In the navigationOptions of our second-level navigator (<strong>Sidebar</strong>) we set the initialRouteName to the next screen in our navigation hierarchy depending on the user’s login status.</p><pre>const Navigator = createStackNavigator({<br>   ...routesObject...<br>  }, <br>    {<br>      <strong>initialRouteName</strong>: (this.props.loggedIn) ? &#39;<strong>Sidebar</strong>&#39; : &#39;<strong>Login</strong>&#39;,<br>    },<br>});</pre><p>In the <strong>Sidebar</strong>, we then move on to the initial route <strong>Router</strong>, whose siblings can be accessed via the DrawerNavigator.</p><pre>const Drawer = createDrawerNavigator({<br>  <strong>Router</strong>: { screen: <strong>Router</strong> }, // another StackNavigator in here<br>  <strong>PastExperiences</strong>: { screen: PastExperiencesScreen },<br>  <strong>FAQ</strong>: { screen: FaqScreen },<br>  <strong>Contact</strong>: { ContactScreen }<br>})</pre><p><em>Inside</em> the router however, the screen we show to the user depends on the current status of her experience. The experience details are part of a subsequent API request that only resolves after the user has logged in.</p><p>This led to another few routing issues that I had to work around and which I’m going to cover next.</p><h4>Challenge #4: showing a nested screen based on an API response without screwing up the user experience</h4><p>Last but not least, I had to solve an issue that was related to how the app interacts with the API. Inside the <strong>Router</strong>, the screen that the user sees is based on an API response from a ride-sharing service.</p><p>The user sees one of the following: <strong>pickup</strong>, <strong>return</strong>,<strong> map </strong>or<strong> evaluation, </strong>based on the current status of the ride that takes her to the restaurant and back.</p><pre>Main -&gt; Sidebar -&gt; <strong>Router</strong> -&gt; Pickup screen<br>                          -&gt; Map<br>                          -&gt; Return screen<br>                          -&gt; Evaluation</pre><p>This sounds easy in theory, but there were three things I had to take care of to prevent the app’s UX from feeling awkward and confusing:</p><ul><li>first, I had to only render the initial screen <em>once</em>. Since we relied on <a href="https://itnext.io/battle-testing-a-ride-sharing-api-and-react-natives-mapview-in-expo-c0ce5d50cbf0">polling</a> to retrieve API updates, every subsequent update should not re-render the router, or it would result in a really annoying flicker effect.</li><li>second, I had to make sure to obtain the ride-sharing update before calling the initial route or opening the app would always result in a transition from the initial (pickup) to the current screen (map, return or evaluation).</li><li>third, I had to take into account that users might background the app for a while and once they come back to the app an update of the current screen should be triggered in case anything changed in the meantime.</li></ul><p><strong>For the first issue</strong>, I used shouldComponentUpdateand wrote some logic that only updated the screen if the actual route changed. This helped me get rid of the flicker effect, even though I recently learned that shouldComponentUpdate should actually not be <a href="https://reactjs.org/docs/react-component.html#shouldcomponentupdate">abused for this kind of purpose</a>.</p><p><strong>For issue number two</strong>, I had to request a little API change that would return the status of the user in the <em>initial</em> response from the server (one that wasn’t initially designed for that purpose). But I also had to make sure the screen wouldn’t show up before evaluating the response. So I had to use the technique I already used in Challenge 2, returning a LoadingScreen as long as other logic is being executed in the component lifecycle.</p><p>For those living on the cutting-edge of technology, <a href="https://blog.logrocket.com/async-rendering-in-react-with-suspense-5d0eaac886c8">React Suspense</a> is going to help with that kind of async rendering in the future.</p><p><strong>For the third issue</strong> (by far the trickiest), I had to wrap the router inside another React component to make sure an update occurs after the app has been backgrounded.</p><p>Because my previously mentioned prevention logic (shouldComponentUpdate) also kept users stuck in the current screen, I had to make sure the component containing the router renders a new router whenever an update occurs.</p><p>This is roughly what the stateless functional component looks like. It creates a new StackNavigator under two conditions:</p><ul><li>the initialRouteName has changed</li><li>no RouterStack has been defined before.</li></ul><pre>let RouterStack;<br>let lastRouteName</pre><pre>const <strong>RouterStackWithInitialRoute</strong> = ({ initialRouteName }) =&gt; {<br>  if (RouterStack === null || lastRouteName !== initialRouteName) {<br>    lastRouteName = initialRouteName;<br>    <strong>RouterStack</strong> = createStackNavigator(<br>      require(&#39;../../../constants/routeConfig&#39;).default,<br>      {<br>        initialRouteName,<br>      });<br>     }<br>  return &lt;<strong>RouterStack</strong> /&gt;;<br>};</pre><p>Passing the initial route name into that component looks as follows:</p><pre>render() {<br>  return this.state.loading ?<br>    &lt;LoadingScreen /&gt; :<br>    &lt;RouterStackWithInitialRoute <br>      <strong>initialRouteName={this.state.initialRouteName}</strong> /&gt;;<br>}</pre><p>Now every time the user comes back to the app, she’ll immediately see the screen that corresponds to the current status of her experience.</p><blockquote>Please keep in mind that all code examples are just a simplification of the actual code to illustrate the point I want to make. So no guarantee that they are going to work in case you try to copy/paste any of them :)</blockquote><h3>Takeaways from building a <em>seemingly</em> simple mobile app in React Native</h3><p>That’s it for my series on building the mobile app for uncovercity.</p><p>I have to admit that judging by the initial user journey I wouldn’t have anticipated such a high level of complexity for something that seems so simple on the surface. And I probably didn’t always come up with the most elegant solution for each of these problems either.</p><p>But taking into account all the possible user scenarios and API issues that surfaced during the project under real-life conditions, it’s very easy to underestimate the effort that needs to go into a project like this.</p><p>The actual work that goes into shipping a battle-tested, bug-free mobile app can grow exponentially if you have to deal with third-party APIs, community-driven libraries and a cutting edge technology like React Native.</p><p>If you happen to be in Spain, you can find the app in the <a href="https://itunes.apple.com/us/app/uncovercity/id1394531362?l=es&amp;ls=1&amp;mt=8">iOS</a> and <a href="https://play.google.com/store/apps/details?id=com.uncovercity.app&amp;hl=de">Google</a> app stores. Just make sure to book a table on to get the full app experience :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fef52ca72964" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-intricacies-of-nesting-navigators-in-react-native-using-react-navigation-fef52ca72964">The intricacies of nesting navigators in React Native using react-navigation</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supporting multiple languages in React Native with Expo’s Localization module]]></title>
            <link>https://itnext.io/supporting-multiple-languages-in-react-native-with-expos-localization-module-9611f9e3b6a0?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9611f9e3b6a0</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Mon, 05 Nov 2018 22:33:19 GMT</pubDate>
            <atom:updated>2018-12-05T10:13:24.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nSzr8tnGo9QEXqhQ" /><figcaption>“Hola LED signage” by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>This is the third post in a 4-part series about building the iOS and Android app for </strong><a href="https://uncovercity.com/"><strong>uncovercity</strong></a><strong> using React Native. You can find the other ones here:</strong></p><ol><li><a href="https://itnext.io/speeding-up-the-build-of-a-surprise-dinner-app-in-react-native-using-expo-2c18beabaaa7">Speeding up the build of a surprise dinner app in React Native using Expo</a></li><li><a href="https://itnext.io/battle-testing-a-ride-sharing-api-and-react-natives-mapview-in-expo-c0ce5d50cbf0?source=your_stories_page---------------------------">Battle testing a ridesharing API and React Native’s MapView in Expo</a></li><li>Supporting multiple languages in React Native with Expo Localization</li><li><a href="https://medium.com/@marcelkalveram/the-intricacies-of-nesting-navigators-in-react-native-using-react-navigation-fef52ca72964">The intricacies of nesting navigators in React Native using react-navigation</a></li></ol><p>Hi! Here’s another post about my experience of building the iOS and Android app for the surprise dinner startup <a href="https://uncovercity.com/">uncovercity</a>. Today, I’m going to walk you through the challenge of translating all the app’s content (texts, videos, images) from Spanish to English.</p><p>Since the app is based on <a href="https://facebook.github.io/react-native/">React Native</a> and <a href="https://expo.io/">Expo</a>, the most obvious thing to do was to look for some existing solution in the ecosystems of these two tools.</p><p>And voilà, Expo has a <a href="https://docs.expo.io/versions/v30.0.0/sdk/localization">Localization</a> module. Though it’s still in the DangerZone (a namespace that Expo uses to group features that haven’t been fully approved yet), I was pleased to have a solid starting point for my challenge.</p><blockquote><strong>IMPORTANT: this blog post is based on Expo version 30.0.0 and below. Expo recently released </strong><a href="https://blog.expo.io/expo-sdk-v31-0-0-is-now-available-cad6d0463f49"><strong>version 31.0.0</strong></a><strong> which includes a complete overhaul of the </strong><a href="https://docs.expo.io/versions/v31.0.0/sdk/localization"><strong>Localization</strong></a><strong> module. The most significant change is that you can now retrieve localisation information from your device synchronously instead of the asynchronous way I’ll be covering in this blog post</strong></blockquote><p>If you’re already familiar with the basics, you can directly skip to the <a href="#ddd6">Common pitfalls</a> where I talk about some more advanced localisation topics.</p><blockquote>If you’re using React Native without Expo, you can get something similar to the Localization module with <a href="https://github.com/react-community/react-native-languages">react-native-languages</a>. However for the actual task of string translation you’d still need something like <a href="https://github.com/i18next/react-i18next">react-i18next</a>.</blockquote><h3>The basics of localisation</h3><p>The <a href="https://docs.expo.io/versions/v30.0.0/sdk/localization">documentation that Expo provides</a> for this module is very bare-bones and convoluted (which is what motivated me to write this post). But implementing it is actually pretty straightforward. All you need to do is:</p><ol><li>create a JSON file for each language you want to provide</li><li>initialise the language store using Expo’s Localizaton module</li><li>set the user’s current language on the store</li><li>replace all the content in your app with the store’s corresponding keys</li></ol><blockquote><strong>For a complete example of the following code in action, please check out the </strong><a href="https://snack.expo.io/@marcelkalveram/localizaton-example"><strong>Snack I’ve created</strong></a><strong> where I initialise a string store from a separate file and add a little toggle button to switch between US English and Spanish.</strong></blockquote><p>Now let me walk you through each of these steps in more detail:</p><h4>1. Create a JSON file for each language</h4><p>The first thing you need to do is put all of your translatable strings into a JSON store. It doesn’t matter if you do that in the same file, or if you import them from a separate file using import. I’ll explain why I prefer the latter in step 2.</p><pre>const <strong>localizedStrings</strong> = {<br>  en_GB: { title: &quot;Hello&quot;, subtitle: &quot;Welcome&quot; },<br>  es_ES: { title: &quot;Hola&quot;, subtitle: &quot;Bienvenido&quot; }<br>}</pre><p>The keys of this object are the language/region identifiers (ie. en_GB stands for English/Great Britain) and the value of a key are all the translatable strings you will have available after the store has been initialised, ie. localeStore.subtitle will output “Bienvenido” if your language has been set to Spanish (es_ES).</p><h4>2. Initialise the store using Expo’s Localizaton module</h4><p>Second, we initialise the store and run the initialisation logic on it. Import the Localization module from Expo like this:</p><pre>import { DangerZone } from &#39;expo&#39;<br>const { <strong>Localization</strong> } = DangerZone</pre><pre>// localizedStrings is the object we created in step 1<br>const localeStore = new Localization.LocaleStore(<strong>localizedStrings</strong>)</pre><p>It’s easier if you put this line of code where your localised strings reside, so you have access to them anywhere you need. So instead of exporting the JSON object directly, export the instantiated store like this:</p><pre>const localeStore = new Localization.LocaleStore(<strong>localizedStrings</strong>)<br><strong>export default</strong> localeStore;</pre><p>This localeStore now gives us access to two important functions:</p><ul><li>setting the current locale we want to show to our users (see next step)</li><li>using the localised strings in our views like this: { <strong>localeStore</strong>.title }</li></ul><h4>3. Set the user’s current language on the store</h4><p>Next, we need to figure out what the user’s preferred language is. We can use the getCurrentLocaleAsync function from the Localization module which returns a language/region identifier. Then, we pass this value on to our previously initialised store using setLocale.</p><pre>import { localeStore } from &quot;./localeStore&quot;<br>...<br>constructor() {<br>  super();<br>  <strong>Localization.getCurrentLocaleAsync()</strong>.then(currentLocale =&gt; <br>    <strong>localeStore.setLocale(locale)</strong><br>  );<br>}</pre><p>The getCurrentLocaleAsync<strong> </strong>function returns the user device’s language/region identifier as a string (which you should be familiar with by now), ie: en_GB It’s an asynchronous call, so we need to make sure that wherever we place this, it needs to be executed this way, either using async/await or a Promise.</p><blockquote>Keep in mind that instead of using <em>getCurrentLocaleAsync</em>, you could as well get access to the device’s <strong>country code</strong> or <strong>preferred locales </strong>by using their respective functions <em>getCurrentDeviceCountryAsync</em> or <em>getPreferredLocalesAsync</em>.</blockquote><p>In addition to that, you probably want to use some kind of state management solution or the React Context API to make your current locale available elsewhere and not only in the root component’s state.</p><h4>4. Replace all translatable strings</h4><p>Last but not least, we need to make sure to use the localised strings from our store instead of the hardcoded strings in our UI views.</p><pre>// we want to replace this...<br>&lt;Text&gt;<strong>Hello</strong>&lt;/Text&gt;</pre><pre>// ...with that:<br>&lt;Text&gt;<strong>{ localeStore.title }</strong>&lt;/Text&gt;</pre><p>This is as simple as it can get in terms of internationalisation. For more advanced translation functions like plurals and formatting, you’d probably want to use a more complete library like react-i18next (which by the way <a href="https://github.com/i18next/react-i18next/tree/master/example/reactnative-expo">works perfectly fine</a> in conjunction with Expo’s Localization module, but is also way more complex).</p><h3>Common pitfalls and their fixes</h3><p>That all sounds pretty straightforward. But there are some less obvious issues that you only run into if you build out a fully localised app with multiple screens and a bit of interaction.</p><h4>Setting and applying the default language</h4><p>You might wonder what happens if the user’s language isn’t covered by any of your translation files and you do something like setLocale(<strong>locale</strong>) where the <strong>locale</strong> you’re trying to set doesn’t exist.</p><p>Or what if you want to provide the same translation for both, en_GB and en_US but prefer not to duplicate the entire array of strings?</p><p>The most simple solution that’s worked for me is to explicitly set the locale based on some condition, instead of just passing the locale blindly to the store’s setLocale function.</p><pre><strong>// instead of blindly relying on this...<br></strong>Localization.getCurrentLocaleAsync().then(currentLocale =&gt; <br>  localeStore.setLocale(currentLocale)<br>);</pre><pre><strong>// ...make sure to explicitly set one of your existing locales<br></strong>Localization.getCurrentLocaleAsync().then(currentLocale =&gt; {<br>  const <strong>locale</strong> = currentLocale.includes(&#39;es&#39;) ? &#39;<strong>es_ES</strong>&#39; : &#39;<strong>en_GB</strong>&#39;; <br>  localeStore.setLocale(<strong>locale</strong>)<br>);</pre><p>In addition to that, you probably want to safeguard your view from rendering anything before we haven’t assigned the user’s default locale first:</p><pre>if (!<strong>this.state.currentLocale</strong>) {<br>  return;<br>}</pre><pre>return &lt;App /&gt;</pre><h4>Switching between languages</h4><p>Now that we know how to set a default language, what if the user actually wants to switch to another language?</p><p>Calling setLocale on the localeStore and updating our state to the new language should do the trick:</p><pre>localeStore.setLocale(<strong>newlocale</strong>)</pre><p>Unfortunately, our views won’t update as a result. How disappointing!</p><p>That’s because the localeStore update happens outside the realm of React state, so React won’t re-render anything. Plus, setLocale is an asynchronous call, so any changes we want to apply after the update has happened need to be handled in the callback function it takes as its second argument.</p><pre>localeStore.setLocale(locale, <br>  <strong>() =&gt; this.setState(() =&gt; ({ currentLocale: locale })))</strong><br>});</pre><p>Now our components will react to the state change and update accordingly.</p><h4>Navigation titles with react-navigation</h4><p>If you’ve worked with react-navigation before, you’re probably familiar with the static navigationOptionsobject that allows you to modify the style and content of the header bar.</p><p>Turns out that since it is a static property, any properties you set inside of it will be evaluated <em>before</em> we set our initial language, and not when the actual screen is mounted.</p><pre>static navigationOptions = {<br>  title: localeStore.title <strong>// this won&#39;t re-render</strong><br>}</pre><p>The solution here is to return a function that returns an object. Like this, every time there’s a state change in our app (like the one triggered by the setLocale callback), these props are going to be updated as well.</p><pre>static navigationOptions = () =&gt; {<br>  <strong>return {</strong><br>    title: localeStore.title <strong>// this uses the updated locale</strong><br>  <strong>}</strong><br>}</pre><h3>Advanced localisation solutions</h3><p>Expo’s Localization module is quite limited. It gives you access to the user device’s language and lets you translate an object of strings based on that.</p><p>That’s probably all you need for many smaller projects. But if your app gets a little more complex than that and you want internationalisation options like placeholders, pluralisation and currency/timezone formatting you might want to look into one the following, more sophisticated solutions:</p><ul><li><a href="https://github.com/i18next/react-i18next">GitHub - i18next/react-i18next: Internationalization for react done right. Using the i18next i18n ecosystem.</a></li><li><a href="https://github.com/fnando/i18n-js">fnando/i18n-js</a></li><li><a href="https://github.com/yahoo/react-intl">yahoo/react-intl</a></li></ul><p>Have you ever translated a React Native app to multiple languages? What has your experience been like? Which tools did you use and what kind of issues did you run into?</p><p>Hope you enjoyed this post and found it helpful. If you have any feedback, please feel free to add a comment. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9611f9e3b6a0" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/supporting-multiple-languages-in-react-native-with-expos-localization-module-9611f9e3b6a0">Supporting multiple languages in React Native with Expo’s Localization module</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Battle testing a ridesharing API and React Native’s MapView in Expo]]></title>
            <link>https://itnext.io/battle-testing-a-ride-sharing-api-and-react-natives-mapview-in-expo-c0ce5d50cbf0?source=rss-8cf85b05864c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0ce5d50cbf0</guid>
            <category><![CDATA[lean]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Marcel Kalveram]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 14:01:02 GMT</pubDate>
            <atom:updated>2018-12-03T08:51:02.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eo19YuJgnxQAn4-5" /><figcaption>“iPhone on vehicle phone holder” by <a href="https://unsplash.com/@samuelfoster?utm_source=medium&amp;utm_medium=referral">Samuel Foster</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>This is the second post in a 4-part series about building the iOS and Android app for </strong><a href="https://uncovercity.com/"><strong>uncovercity</strong></a><strong> using React Native. You can find the other ones here:</strong></p><ol><li><a href="https://itnext.io/speeding-up-the-build-of-a-surprise-dinner-app-in-react-native-using-expo-2c18beabaaa7">Speeding up the build of a surprise dinner app in React Native using Expo</a></li><li>Battle testing a ridesharing API and React Native’s MapView in Expo</li><li><a href="https://medium.com/@marcelkalveram/supporting-multiple-languages-in-react-native-with-expos-localization-module-9611f9e3b6a0">Supporting multiple languages in React Native with Expo Localization</a></li><li><a href="https://medium.com/@marcelkalveram/the-intricacies-of-nesting-navigators-in-react-native-using-react-navigation-fef52ca72964">The intricacies of nesting navigators in React Native using react-navigation</a></li></ol><h3>Battle testing a ridesharing API and React Native’s MapView in Expo</h3><p>Recently, I had the pleasure to experiment with maps and API integration in React Native while working on the iOS app for <a href="https://uncovercity.com/">uncovercity.com</a>.</p><p>The challenge can be summarised very easily:</p><ol><li>a car (ordered via a ride-sharing app like Uber) picks you up at a specific location and takes you to a surprise dinner at an unknown venue.</li><li>when your dinner is over, you can use the app to order a ride home.</li></ol><p>What made the challenge interesting was that we were forced to test the ride-sharing part of the app in production from the start, so we were constantly in touch with drivers and sitting in fancy cars with a phone in our hands and a computer on our laps.</p><h3>The challenge</h3><p>To make the experience as pleasant and predictable as possible for the user, we implemented a live map showing the current position of the vehicle when it’s underway, for both the pickup and the return journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*F5OqWxY_RV_cFa0OoL8O7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*aKyIaJ3ufYwJEvUx6cqfZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*yXvpjpgTIUz3TGQ5Jgl8Xw.png" /><figcaption>Some screenshots of the uncovercity app on the iPhone X. From left to right: searching for a ride, pick-up at the restaurant, return journey home</figcaption></figure><p>In the screenshots above, you can see the different states of the app:</p><ul><li>searching vehicle: after the user requested the return journey</li><li>pickup journey: when the vehicle is on its way to pick up the user at home</li><li>return journey: the vehicle on its way to pick up the user at the restaurant</li></ul><p>In this post, I’m going to talk about how we did this and what challenges we faced.</p><h3>The solution</h3><p>The technical solution involves three main components:</p><ul><li><a href="https://redux.js.org/">Redux</a> to update the vehicle position on the map every time we get a response from the API</li><li><a href="https://github.com/gaearon/redux-thunk">Redux Thunk</a> actions that dispatch asynchronous API requests to trigger a response from the server (due to limitations, this had to be done via polling)</li><li>an API proxy that would communicate with the ride-sharing service and filter/map the data according to our needs.</li><li>Expo’s <a href="https://docs.expo.io/versions/latest/sdk/map-view">MapView</a> component (which is based on the React Community’s <a href="https://github.com/react-community/react-native-maps">React Native component</a>) to show a marker with the current coordinates of the vehicle and the icons of the home and restaurant location.</li></ul><h3>Working around an unfinished API</h3><p>The API proxy sounds like a weird thing to do, but we actually had to put that layer in between our app and the ride-sharing API for several reasons. There were cases when no vehicles would be available, and we couldn’t rely on the app itself to send another request (because it could be inactive). Instead, a cron job handled that task.</p><p>Unfortunately, at the time we built the app there was also no way to use the ride-sharing API’s websocket integration which would push status updates to the app. So we had to go for good ol’ polling and send requests to the server every few seconds to obtain the current location data. Since we didn’t expect there to be tons of requests per hour, this seemed a viable solution for the beginning, even though not a very scalable one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bg8_r1e7yizmuj1Ipw90og.png" /><figcaption>A simplified overview of the app’s data flow: from UI component to Redux to API and back</figcaption></figure><p>Things got more complicated when we found out that the ride-sharing service’s testing environment was still in development. So any possible scenario (ride ordered, car on the road, car arrived, all drivers busy, etc…) we needed to respond to in our own product could only be tested in production! More on that later…</p><h3>Displaying markers with Expo’s MapView component</h3><p>The experience of working with Expo’s <a href="https://docs.expo.io/versions/latest/sdk/map-view">MapView</a> to display live markers on the map is pretty straightforward (I’ve removed some noise from this snippet to make it clearer).</p><pre>&lt;MapView&gt;<br>    &lt;MapView.<strong>Marker</strong><br>      identifier=&quot;vehiclePosition&quot;<br>      coordinate={{<br>        latitude: this.props.location[0],<br>        longitude: this.props.location[1]<br>      }}<br>      image={ICON_MAP}<br>    /&gt;<br>    &lt;MapView.<strong>Marker</strong><br>      identifier=&quot;restaurantPosition&quot;<br>      coordinate={{<br>        latitude: experience.local_latitude,<br>        longitude: experience.local_longitude<br>      }}<br>      image={ICON_RESTAURANT}<br>    /&gt;<br>&lt;/MapView&gt;</pre><p>Updating coordinates is also really simple:</p><ul><li>A JavaScript interval fires a redux-thunk event to dispatch a new API request every second.</li><li>The response then gets processed by a redux reducer and the data sent to the view.</li><li>Once the MapView <a href="https://github.com/react-community/react-native-maps/blob/master/docs/marker.md">Marker</a> receives the new coordinates, it updates its position instantly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*jeAs2o1vOq24-Ja4nQf5ag.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*XSFqxeS02XImJfksU8MM7Q.gif" /><figcaption>As the map udpates the position of the car, it automatically adjusts its viewport to center the relevant icons</figcaption></figure><h3>Fitting the map to a set of supplied markers</h3><p>The MapView component also makes it easy to focus the map on a set of markers and animate it smoothly to show the corresponding area of the map with every update, using its <a href="https://github.com/react-community/react-native-maps/blob/master/docs/mapview.md#methods">fitToSuppliedMarkers</a> method.</p><p>Unfortunately though, the method doesn’t allow for any padding (unlike its <a href="https://github.com/react-community/react-native-maps/blob/master/docs/mapview.md#methods">fitToCoordinates</a>counterpart) to make sure the markers don’t overlap with other elements on the screen.</p><p>Luckily, the <a href="https://github.com/react-community/react-native-maps/issues/1149#issuecomment-344883668">community provides a solution</a> that’s very easy to implement:</p><pre>fitToSuppliedMarkersCustom(coordinates) {<br>  const markers = [];<br>  markers.push(this.vehicleCoordinates());<br>  markers.push(coordinates);</pre><pre>  this.map.<strong>fitToCoordinates</strong>(markers, {<br>    edgePadding: {<br>      bottom: 200, right: 50, top: 150, left: 50,<br>    },<br>    animated: true,<br>  });<br>}</pre><p>All you have to do is store the markers’ reference using React’s <a href="https://reactjs.org/docs/refs-and-the-dom.html">ref</a> attribute, push them to an array and use the <a href="https://github.com/react-community/react-native-maps/blob/master/lib/components/MapView.js#L594">fitToCoordinates</a> method instead.</p><blockquote>Update: I recently created a <a href="https://github.com/react-community/react-native-maps/pull/2479">pull request</a> on the <a href="https://github.com/react-community/react-native-maps">react-native-maps</a> repo that fixes this behaviour and allows you to pass the <strong>edgePadding</strong> object directly into <a href="https://github.com/react-community/react-native-maps/blob/master/lib/components/MapView.js#L585">fitToSuppliedMarkers</a>. The PR has been approved and merged into master.</blockquote><h3>Testing our scrappy solution</h3><p>As you can imagine, the first few attempts of properly syncing the API responses with the UI were pretty unsuccessful. That’s not a big deal when you use a testing environment and your requests don’t have any impact on the real world. Our case though was that every time we “tested” the API, we’d request a real vehicle.</p><p>What worked in our favour though was that the ride-sharing service provides a 30-second courtesy time of cancelling a ride, not the most ideal feature for drivers, but at least it would allow us to adjust and fine-tune our system, with the minor downside of sending drivers to random destinations all the time.</p><p>I actually ended up in the car of a driver who complained about our request/cancel approach of bulletproofing their service’s API. But despite making some drivers really mad at us and even though we didn’t develop the most elegant solution (using polling, testing in production, relying on cron jobs), it actually works solidly now, and we managed to bootstrap our way through limited resources and unexpected constraints to a production-ready app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0ce5d50cbf0" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/battle-testing-a-ride-sharing-api-and-react-natives-mapview-in-expo-c0ce5d50cbf0">Battle testing a ridesharing API and React Native’s MapView in Expo</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>