<?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 Ankit Dhawan on Medium]]></title>
        <description><![CDATA[Stories by Ankit Dhawan on Medium]]></description>
        <link>https://medium.com/@ankit.ad.dhawan?source=rss-209d72b16940------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KGcu4fGBQPYwnR3ktHQA6g.jpeg</url>
            <title>Stories by Ankit Dhawan on Medium</title>
            <link>https://medium.com/@ankit.ad.dhawan?source=rss-209d72b16940------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:38:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit.ad.dhawan/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[Stop hand-editing Gradle flavors and Xcode schemes: one YAML file for every React Native…]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/stop-hand-editing-gradle-flavors-and-xcode-schemes-one-yaml-file-for-every-react-native-48de9fb35650?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/48de9fb35650</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javscript]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 13:57:17 GMT</pubDate>
            <atom:updated>2026-09-23T13:57:17.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop hand-editing Gradle flavors and Xcode schemes: one YAML file for every React Native environment</h3><p>Every React Native app eventually needs more than one environment. A dev build pointing at a local API, a staging build for QA, a production build for the store. Getting there means product flavors in build.gradle, a matching set of Xcode schemes and configurations, distinct bundle IDs so all three can sit on the same device, and some way to get the right base URL into your JavaScript.</p><p>It’s an afternoon of work the first time. It’s an afternoon of work again every time someone adds an environment, and it’s the kind of setup that quietly rots when one person edits the Android side and forgets iOS.</p><p>I built <a href="https://www.npmjs.com/package/rn-env-setup"><strong>rn-env-setup</strong></a> to collapse that into one config file and one command.</p><p>Docs: <a href="https://rn-env-setup.netlify.app/">https://rn-env-setup.netlify.app/</a></p><h3>Install</h3><p>bash</p><pre>npm install -g rn-env-setup</pre><p>Or skip the global install and use npx:</p><p>bash</p><pre>npx rn-env-setup init</pre><h3>The whole flow</h3><p>From the root of your React Native app:</p><p>bash</p><pre>cd your-react-native-app<br>npx rn-env-setup init<br>npx rn-env-setup validate<br>npx rn-env-setup generate</pre><p>init walks you through an interactive setup and writes an rn-env.yaml. validate checks the config without touching anything. generate applies the Android + iOS + JS env generation and adds helper scripts to your app&#39;s package.json.</p><h3>One file describes everything</h3><p>yaml</p><pre>appName: MyApp<br>packageName: com.myapp<br>jsEnvStrategy: react-native-config<br>generateJsEnv: true<br>generateCiSnippets: false<br>enableRollback: true</pre><pre>environments:<br>  - name: dev<br>    appName: MyApp Dev<br>    bundleId: com.myapp.dev<br>    apiUrl: <a href="https://dev.api.example.com/">https://dev.api.example.com</a><br>    variables:<br>      FEATURE_NEW_UI: true</pre><pre>  - name: staging<br>    appName: MyApp Staging<br>    bundleId: com.myapp.staging<br>    apiUrl: <a href="https://staging.api.example.com/">https://staging.api.example.com</a></pre><pre>  - name: prod<br>    appName: MyApp<br>    bundleId: com.myapp<br>    apiUrl: <a href="https://api.example.com/">https://api.example.com</a></pre><p>Three environments, three bundle IDs, three display names, three API URLs. Adding a fourth is four lines and a re-run.</p><p>Nervous about what it will touch? Preview first:</p><p>bash</p><pre>npx rn-env-setup generate --dry-run</pre><p>And if you want to scope it to one platform while you’re testing:</p><p>bash</p><pre>rn-env-setup generate --android-only<br>rn-env-setup generate --ios-only</pre><h3>What you get back</h3><p>After generate, your package.json has scripts like these:</p><pre>env:android:run:dev<br>env:android:apk:dev:debug<br>env:android:apk:dev:release<br>env:android:aab:dev:release<br>env:ios:run:dev</pre><p>Plus the equivalents for every environment name you defined. So running staging is no longer a paragraph in the onboarding doc:</p><p>bash</p><pre>npm run env:android:run:dev<br>npm run env:ios:run:dev</pre><p>Swap dev for staging or prod. Release artifacts work the same way:</p><p>bash</p><pre>npm run env:android:apk:dev:release<br>npm run env:android:aab:dev:release</pre><h3>Reading the values in your code</h3><p>Each environment’s apiUrl and variables come through to JavaScript. With jsEnvStrategy: react-native-config:</p><p>ts</p><pre>import Config from &#39;react-native-config&#39;;</pre><pre>const baseUrl = Config.API_URL;<br>const featureFlag = Config.FEATURE_NEW_UI;</pre><p>If you’d rather not add that dependency, set jsEnvStrategy: custom and import the generated file instead:</p><p>ts</p><pre>import Config from &#39;./src/env&#39;;</pre><pre>const baseUrl = Config.API_URL;</pre><p>Same call site, different source. The feature flags you put under variables come through alongside the URL, so per-environment toggles don&#39;t need their own mechanism.</p><h3>Firebase per environment</h3><p>This is where most multi-environment setups get stuck. Because each environment is a real Android flavor, you can drop in flavor-specific config files:</p><pre>android/app/src/dev/google-services.json<br>android/app/src/staging/google-services.json<br>android/app/src/prod/google-services.json</pre><p>With a fallback at android/app/google-services.json if you want one. Your Android Firebase Gradle setup needs to already be in place (the com.google.gms.google-services plugin and its classpath). On iOS, keep per-environment GoogleService-Info.plistfiles and select the right one per scheme.</p><h3>Testing across environments</h3><p>Because the config is data, your tests can iterate over it:</p><p>ts</p><pre>const envs = [&#39;dev&#39;, &#39;staging&#39;, &#39;prod&#39;];</pre><pre>envs.forEach((env) =&gt; {<br>  test(`API URL exists for ${env}`, () =&gt; {<br>    process.env.ENV = env;<br>    // load env config and assert URL/flags<br>  });<br>});</pre><p>The pattern that’s worked for me: unit tests validate the env config mapping and feature flags, integration tests mock the API client per environment base URL, and E2E runs per environment build in a CI matrix.</p><h3>If something goes wrong</h3><p>Generation backs up the files it modifies, so:</p><p>bash</p><pre>rn-env-setup rollback</pre><p>restores them.</p><h3>Where to read more</h3><p>Full CLI reference, every config field, and the complete FAQ are on the docs site: <a href="https://rn-env-setup.netlify.app/">https://rn-env-setup.netlify.app/</a></p><p>The package is on npm: <a href="https://www.npmjs.com/package/rn-env-setup"><strong>rn-env-setup</strong></a>. MIT licensed.</p><p>If you try it and hit a case it doesn’t cover, I’d like to hear about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48de9fb35650" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built RNFlow because drawing a tree in React Native is harder than it should be]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/i-built-rnflow-because-drawing-a-tree-in-react-native-is-harder-than-it-should-be-666476aa0ad8?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/666476aa0ad8</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flowchart]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 11:48:15 GMT</pubDate>
            <atom:updated>2026-09-20T11:48:15.371Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>An interactive tree and flow diagram component for React Native, with pinch-zoom, custom node rendering, and no web view.</strong></p><p>Org charts, family trees, decision flows, file browsers. They all come down to the same problem: you have a node with children, and you want it on screen in a way a user can explore with their thumb.</p><p>On the web you reach for React Flow and move on. On React Native the options thin out fast. You end up either embedding a web view, which costs you native feel and performance, or hand-rolling layout math and SVG paths on a deadline.</p><p>So I wrote <strong>RNFlow</strong>. You give it a root node. It handles layout, edges, pinch-zoom and panning.</p><h3>Install</h3><pre>npm install react-native-rnflow react-native-svg react-native-gesture-handler react-native-reanimated</pre><p>Three peer dependencies, all of them ones you probably already have. They each need native setup, so work through the installation steps in order rather than skipping ahead.</p><p>Two easy things to get wrong:</p><p>Add the Reanimated plugin to babel.config.js, and make sure it is last in the list:</p><p>javascript</p><pre>module.exports = {<br>  presets: [&#39;module:metro-react-native-babel-preset&#39;],<br>  plugins: [<br>    &#39;react-native-reanimated/plugin&#39;, // MUST be last<br>  ],<br>};</pre><p>And import Gesture Handler at the very top of index.js:</p><p>javascript</p><pre>import &#39;react-native-gesture-handler&#39;;</pre><p>Get either wrong and you’ll see the classic symptoms: gestures that don’t respond, or zoom that snaps instead of animating.</p><h3>The smallest thing that works</h3><p>tsx</p><pre>import RNFlow, { RNFlowNode } from &#39;react-native-rnflow&#39;;</pre><pre>const data: RNFlowNode = {<br>  id: &#39;1&#39;,<br>  data: { title: &#39;CEO&#39; },<br>  children: [<br>    { id: &#39;2&#39;, data: { title: &#39;CTO&#39; } },<br>    { id: &#39;3&#39;, data: { title: &#39;CFO&#39; } },<br>  ],<br>};</pre><pre>function App() {<br>  return &lt;RNFlow data={data} /&gt;;<br>}</pre><p>That’s a working, zoomable org chart. No layout config, no measuring, no SVG.</p><h3>Making it yours</h3><p>Props are grouped by concern rather than flattened into thirty top-level props. Layout goes in layout, gestures in zoom, callbacks in interaction, and so on.</p><p>Want a left-to-right tree with bigger nodes and softer edges:</p><p>tsx</p><pre>&lt;RNFlow<br>  data={data}<br>  layout={{<br>    direction: &#39;horizontal&#39;,<br>    nodeWidth: 180,<br>    nodeHeight: 100,<br>  }}<br>  style={{<br>    backgroundColor: &#39;#F5F7FA&#39;,<br>    edgeStyle: {<br>      stroke: &#39;#64B5F6&#39;,<br>      strokeWidth: 2,<br>    },<br>  }}<br>  edgeType=&quot;smoothstep&quot;<br>/&gt;</pre><p>edgeType takes straight, curved, step or smoothstep, which covers most of what a diagram needs to communicate.</p><p>Want to react to taps:</p><p>tsx</p><pre>const [selectedIds, setSelectedIds] = useState&lt;string[]&gt;([]);</pre><pre>&lt;RNFlow<br>  data={data}<br>  selectedNodeIds={selectedIds}<br>  interaction={{<br>    onNodePress: (node) =&gt; {<br>      setSelectedIds([node.id]);<br>      console.log(&#39;Pressed:&#39;, node.data.title);<br>    },<br>    onZoomChange: (zoom) =&gt; console.log(&#39;Zoom:&#39;, zoom),<br>  }}<br>/&gt;</pre><h3>The part I care about most</h3><p>Default nodes are rectangles with a title. Real apps need avatars, badges, status colours, file sizes, birth years. So renderNode hands the whole node back to you:</p><p>tsx</p><pre>&lt;RNFlow<br>  data={data}<br>  render={{<br>    renderNode: (node, { isSelected, onPress, dimensions }) =&gt; (<br>      &lt;TouchableOpacity<br>        onPress={onPress}<br>        style={{<br>          width: dimensions.width,<br>          height: dimensions.height,<br>          backgroundColor: isSelected ? &#39;#E3F2FD&#39; : &#39;#FFF&#39;,<br>          borderRadius: 12,<br>          padding: 16,<br>        }}<br>      &gt;<br>        &lt;Text style={{ fontWeight: &#39;bold&#39; }}&gt;{node.data.title}&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br>    ),<br>  }}<br>/&gt;</pre><p>You get the node, its selection state, press handlers, and the exact dimensions RNFlow reserved for it in the layout. Everything inside is ordinary React Native. That single prop is how the same component renders an org chart, a genealogy tree with photos and dates, and a file browser with icons and sizes.</p><p>[<strong>Insert your screenshots here — the org chart, family tree, knowledge graph, decision tree and file system shots side by side.</strong> They make this point better than the paragraph above does.]</p><h3>Performance</h3><p>Reported render times on my test trees:</p><ul><li>10 nodes: under 100ms, 60fps</li><li>50 nodes: under 300ms, 60fps</li><li>100 nodes: under 600ms, 55 to 60fps</li><li>500 nodes: under 2s, 50 to 55fps</li></ul><p>If you’re pushing into the hundreds, memoize your renderNode, keep node data small and load details on demand, and shrink nodeWidth and nodeHeight.</p><h3>Try it</h3><p>The package ships 21+ ready-to-use examples covering org charts, project roadmaps, network diagrams, mind maps, dark themes and multi-select.</p><ul><li>npm: <a href="https://www.npmjs.com/package/react-native-rnflow">react-native-rnflow</a></li><li>Full documentation: <a href="https://react-native-rnflow.netlify.app/">https://react-native-rnflow.netlify.app/</a></li></ul><p>It’s MIT licensed. If you build something with it, I’d like to see it.</p><p><strong>Placeholders to fill before publishing:</strong></p><ol><li><a href="https://react-native-rnflow.netlify.app/">https://react-native-rnflow.netlify.app/</a> appears once at the end. I can also work the docs link into the intro if you want it higher up.</li><li>The screenshot block in the middle. Medium handles image grids well, so the five shots in one row would work.</li><li>The opening section is written as though the missing-library gap is why you built it. If the real reason was different, that paragraph is the one to rewrite in your own voice.</li></ol><p>I kept out anything I couldn’t back from your README: no download counts, no GitHub stars, no comparisons to specific libraries beyond naming React Flow as the web equivalent. Say the word if you want it shorter, or want a version that leads with the screenshots instead of the problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666476aa0ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI explained]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/server-driven-ui-explained-0ef0b57070df?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ef0b57070df</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 08:30:30 GMT</pubDate>
            <atom:updated>2025-03-23T08:30:30.623Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how your favorite applications like Instagram, Airbnb, Spotify, and WhatsApp change their UI without you even updating the app?</p><p>You might be thinking, “Well, they probably use webviews, right?” And sure, that’s one possibility — but would these tech giants really build their entire apps using webviews just to update the UI more easily? That doesn’t seem like the most efficient approach.</p><p>This is where Server-Driven UI comes into the picture. But what does this term actually mean? Does the server really decide what UI to show? Yes, exactly!</p><p>But wait — aren’t backend developers and servers only meant to transfer data to the frontend? That’s the traditional approach, but Server-Driven UI expands this relationship. The server not only determines what data to display but also controls how that information is visually presented to you as a user. It’s like having a remote control for your app’s appearance, operated from the server side. Pretty clever, right?</p><p>In this article, we will take a deep dive into what Server Driven UI is and how we can use it to update our application interface without releasing any update via on-air or Play Store/App Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wk9rovPYI3_deGe9G8UWdw.png" /></figure><h4>How SDUI works?</h4><p>Server-driven UI revolves around the idea that the server sends a complete description of the UI, both the data and its presentation to the client application. This approach differs from traditional client-server architectures where the client determines how to render data.</p><p>The data can be sent from the backend in a JSON or XML like mentioned below.</p><pre>{<br>    &quot;type&quot;: &quot;listView&quot;,<br>    &quot;styles&quot;: {<br>        &quot;container&quot;: {<br>            &quot;backgroundColor&quot;: &quot;#f8f9fa&quot;,<br>            &quot;padding&quot;: 16<br>        },<br>        &quot;list&quot;: {<br>            &quot;spacing&quot;: 16<br>        }<br>    },<br>    &quot;data&quot;: [{<br>        &quot;id&quot;: &quot;hotel1&quot;,<br>        &quot;componentType&quot;: &quot;hotelCard&quot;,<br>        &quot;properties&quot;: {<br>            &quot;imageUrl&quot;: &quot;https://example.com/hotel1.jpg&quot;,<br>            &quot;title&quot;: &quot;Grand Hotel Plaza&quot;,<br>            &quot;rating&quot;: 4.7,<br>            &quot;description&quot;: &quot;Luxurious 5-star hotel with panoramic city views and world-class amenities.&quot;,<br>            &quot;price&quot;: {<br>                &quot;amount&quot;: 299,<br>                &quot;currency&quot;: &quot;USD&quot;,<br>                &quot;period&quot;: &quot;night&quot;<br>            },<br>            &quot;isFavorite&quot;: false<br>        },<br>        &quot;styles&quot;: {<br>            &quot;card&quot;: {<br>                &quot;backgroundColor&quot;: &quot;white&quot;,<br>                &quot;borderRadius&quot;: 12,<br>                &quot;shadowColor&quot;: &quot;#000&quot;,<br>                &quot;shadowOpacity&quot;: 0.1,<br>                &quot;shadowRadius&quot;: 4,<br>                &quot;elevation&quot;: 3<br>            },<br>            &quot;image&quot;: {<br>                &quot;height&quot;: 200,<br>                &quot;resizeMode&quot;: &quot;cover&quot;<br>            },<br>            &quot;favoriteButton&quot;: {<br>                &quot;position&quot;: &quot;absolute&quot;,<br>                &quot;bottom&quot;: 12,<br>                &quot;left&quot;: 12,<br>                &quot;backgroundColor&quot;: &quot;rgba(0,0,0,0.4)&quot;,<br>                &quot;borderRadius&quot;: 20,<br>                &quot;width&quot;: 40,<br>                &quot;height&quot;: 40<br>            },<br>            &quot;content&quot;: {<br>                &quot;padding&quot;: 16<br>            },<br>            &quot;title&quot;: {<br>                &quot;fontSize&quot;: 18,<br>                &quot;fontWeight&quot;: &quot;600&quot;,<br>                &quot;color&quot;: &quot;#333333&quot;<br>            },<br>            &quot;rating&quot;: {<br>                &quot;fontSize&quot;: 16,<br>                &quot;fontWeight&quot;: &quot;600&quot;,<br>                &quot;color&quot;: &quot;#333333&quot;<br>            }<br>            &quot;description&quot;: {<br>                &quot;fontSize&quot;: 14,<br>                &quot;color&quot;: &quot;#666666&quot;,<br>                &quot;marginBottom&quot;: 12,<br>                &quot;lineHeight&quot;: 20<br>            },<br>            &quot;price&quot;: {<br>                &quot;fontSize&quot;: 20,<br>                &quot;fontWeight&quot;: &quot;700&quot;,<br>                &quot;color&quot;: &quot;#0066cc&quot;<br>            }<br>        }<br>    }]<br>}</pre><p>Here’s a breakdown of the JSON</p><ol><li><strong>type</strong>: It denotes the what the component is like. I have written ‘list’ as the type of the component means it is a scrollable ListView. You can further add directions to it if it is supposed to be a horizontal scroll or vertical scroll.</li><li><strong>styles</strong>: It contains the styles of the root container which will have all the children component. In our case it will be the parent list container and inside that container will have the components individually.</li><li><strong>data</strong>: The data array holds multiple UI components to display inside the list component with the styling that comes with the data to show. Inside data we get the properties object which contains the data to be shown for the Hotel Card and the styles Object contains StyleSheet of the card.</li></ol><h4>How to use the Server Drive UI JSON?</h4><p>To use this JSON we’ll need to map the data received from the API and create a server driven component dynamically.</p><pre>const ServerDrivenUI = ({ jsonData }) =&gt; {<br>  if (!jsonData || jsonData.type !== &quot;listView&quot;) return null;<br><br>  return (<br>    &lt;View style={{ backgroundColor: jsonData.styles.container.backgroundColor, padding: jsonData.styles.container.padding }}&gt;<br>      &lt;FlatList<br>        data={jsonData.data}<br>        keyExtractor={(item) =&gt; item.id}<br>        renderItem={({ item }) =&gt; {<br>          if (item.componentType === &quot;hotelCard&quot;) {<br>            return &lt;HotelCard hotel={item} /&gt;;<br>          }<br>          return null;<br>        }}<br>        contentContainerStyle={{ gap: jsonData.styles.list.spacing }}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><pre>const HotelCard = ({ hotel }) =&gt; {<br>  const { properties, styles } = hotel;<br><br>  return (<br>    &lt;View style={{<br>      backgroundColor: styles.card.backgroundColor,<br>      borderRadius: styles.card.borderRadius,<br>      shadowColor: styles.card.shadowColor,<br>      shadowOpacity: styles.card.shadowOpacity,<br>      shadowRadius: styles.card.shadowRadius,<br>      elevation: styles.card.elevation,<br>      marginBottom: 16<br>    }}&gt;<br>      &lt;Image<br>        source={{ uri: properties.imageUrl }}<br>        style={{ height: styles.image.height, resizeMode: styles.image.resizeMode }}<br>      /&gt;<br>      <br>      {/* Favorite Button */}<br>      &lt;TouchableOpacity style={{<br>        position: styles.favoriteButton.position,<br>        bottom: styles.favoriteButton.bottom,<br>        left: styles.favoriteButton.left,<br>        backgroundColor: styles.favoriteButton.backgroundColor,<br>        borderRadius: styles.favoriteButton.borderRadius,<br>        width: styles.favoriteButton.width,<br>        height: styles.favoriteButton.height,<br>        alignItems: &quot;center&quot;,<br>        justifyContent: &quot;center&quot;<br>      }}&gt;<br>        &lt;Text style={{ color: &quot;white&quot; }}&gt;❤️&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br><br>      {/* Content */}<br>      &lt;View style={{ padding: styles.content.padding }}&gt;<br>        &lt;Text style={{ fontSize: styles.title.fontSize, fontWeight: styles.title.fontWeight, color: styles.title.color }}&gt;<br>          {properties.title}<br>        &lt;/Text&gt;<br>        &lt;Text style={{ fontSize: styles.rating.fontSize, fontWeight: styles.rating.fontWeight, color: styles.rating.color }}&gt;<br>          ⭐ {properties.rating}<br>        &lt;/Text&gt;<br>        &lt;Text style={{ fontSize: styles.description.fontSize, color: styles.description.color, marginBottom: styles.description.marginBottom, lineHeight: styles.description.lineHeight }}&gt;<br>          {properties.description}<br>        &lt;/Text&gt;<br>        &lt;Text style={{ fontSize: styles.price.fontSize, fontWeight: styles.price.fontWeight, color: styles.price.color }}&gt;<br>          {properties.price.currency} {properties.price.amount} / {properties.price.period}<br>        &lt;/Text&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p>This is how we can create a Server-driven dynamic component by using the data and styles from the backend.<br>This is just a basic integration and understanding of how we can dynamically create a React component dynamically by getting the data and styles from the server. This approach can be used further to enhance the JSON structure and the client application which can make the interface efficient and better.</p><h4>Why Server Driven UI?</h4><p>✅ <strong>Dynamic UI Changes:</strong> No need to redeploy apps for UI updates.<br>✅ <strong>Personalization:</strong> Show different UI components based on user data.<br>✅ <strong>A/B Testing &amp; Experiments:</strong> Try different UI layouts without app updates.<br>✅ <strong>Smaller App Size:</strong> UI components are fetched on demand, reducing bundle size.</p><h3>Pros and Cons</h3><p><strong>Pros</strong></p><ul><li>Dynamic UI updates without app releases</li><li>Unified UI logic across platforms</li><li>Simplified A/B testing capabilities</li><li>Reduced maintenance burden for multiple platforms</li><li>Personalization opportunities</li><li>Data-driven UI optimization</li></ul><p><strong>Cons</strong></p><ul><li>Increased network dependency</li><li>Potential performance implications</li><li>Added complexity in the development stack</li><li>Initial development overhead</li><li>Learning curve for teams</li><li>Debugging challenges across client/server boundary</li></ul><p>Now You’ve got an approximate idea what Server-driven UI is and how it works. The possibilities of using Server-driven UI are endless. Depending on the application requirements and complexity, the JSON or XML structure can be changed or further improved to get the best result possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ef0b57070df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to Mobile App Testing]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/complete-guide-to-mobile-app-testing-ce96f75f0946?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce96f75f0946</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[app-testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 12:50:33 GMT</pubDate>
            <atom:updated>2025-02-16T12:50:33.925Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is a crucial part of development and must be done so that mishandling and failures don’t become a major issue in the production environment for the apps. It ensures that the app functions correctly, performs well in any situation, and gives a better user experience. This guide covers the essential topics for mobile app testing in <strong>React Native </strong>using <strong>Jest </strong>to write unit test cases and how to do <strong>Performance Testing</strong> in your Android and iOS mobile applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5o1sxMm_SphUgkKOZNMIiA.png" /><figcaption>Guide to Mobile App Testing</figcaption></figure><h4>Table of Contents</h4><ol><li><a href="#a1e5"><strong>Jest</strong></a><br>1. <a href="#8a16">Installing Jest.</a><br>2. <a href="#3431">Writing Test Cases.</a><br>3. <a href="#adda">Writing Mock Functions.</a><br>4. <a href="#997d">Snapshot Testing.</a><br>5. <a href="#daff">Best File Structure for Test Cases.</a><br>6. <a href="#e884">Running Test cases.</a><br>7. <a href="#3c96">What to test and what not to?</a></li><li><a href="#764c"><strong>Performance testing</strong></a><br><strong>In Android Studio</strong><br> 1. <a href="#61e5">Profiler</a><br> 2. <a href="#05cc">GPU Rendering Profile</a><br> 3. <a href="#a88d">Network Throttling</a><br><strong>In Xcode<br> </strong>1. <a href="#7fb4">Instruments</a><br> 2. <a href="#0726">Leaks Instrument</a><br> 3. <a href="#c757">Time Profiler</a></li></ol><h3>Using Jest to Write Test Cases</h3><blockquote>Jest is a popular testing framework for JavaScript applications, including React Native apps. It is fast, easy to configure, and provides powerful mocking capabilities.</blockquote><h4>Installing Jest</h4><pre>npm install --save-dev jest react-test-renderer @testing-library/react-native<br>or<br>yarn add --dev jest react-test-renderer @testing-library/react-native</pre><p>Add this to <strong>package.json</strong></p><pre>{<br>  &quot;jest&quot;: {<br>    &quot;preset&quot;: &quot;react-native&quot;<br>  }<br>}</pre><h4>Writing Test Cases</h4><p>To write a test case, you need to create a file with extension <strong>test.tsx</strong> or <strong>test.js</strong> inside the <strong>__tests__</strong> directory</p><p>Here’s a simple test case for the <strong>Button</strong> (Button.test.js) component, which checks if the button is rendered correctly and functions correctly or not.</p><pre>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react-native&#39;;<br>import Button from &#39;../components/Button&#39;;<br><br>test(&#39;Button calls onPress when clicked&#39;, () =&gt; {<br>  const mockOnPress = jest.fn();<br>  const { getByText } = render(<br>    &lt;Button title=&quot;Click Me&quot; onPress={mockOnPress} /&gt;<br>  );<br><br>  //Checks if the button with the text renders or not<br>  expect(getByText(&#39;Click Me&#39;)).toBeTruthy();<br><br>  //Checks if the function is called after clicking the button or not<br>  fireEvent.press(getByText(&#39;Click Me&#39;));<br>  expect(mockOnPress).toHaveBeenCalledTimes(1);<br>});</pre><h4>Writing Mock Functions</h4><blockquote>Mock functions allow us to simulate function calls without executing the actual implementation. Jest provides built-in mocking capabilities using <strong>jest.fn()</strong> and <strong>jest.mock()</strong></blockquote><p><strong><em>Mocking a Function</em></strong></p><pre>const mockFunction = jest.fn();<br>mockFunction(&#39;Hello&#39;);<br>mockFunction(&#39;World&#39;);<br><br>//Checks that the mockFunction is called twice or not<br>expect(mockFunction).toHaveBeenCalledTimes(2);<br><br>//Checks if the mockFunction is called with correct value<br>expect(mockFunction).toHaveBeenCalledWith(&#39;Hello&#39;);<br>expect(mockFunction).toHaveBeenCalledWith(&#39;World&#39;);</pre><p><strong><em>Mocking API Calls</em></strong></p><pre>import axios from &#39;axios&#39;;<br>jest.mock(&#39;axios&#39;);<br><br>test(&#39;fetches data from API&#39;, async () =&gt; {<br>  axios.get.mockResolvedValue({ data: { message: &#39;Success&#39; } });<br>  <br>  const response = await axios.get(&#39;/api/data&#39;);<br>  //Checks if the response of the API is &#39;Success&#39; or not<br>  expect(response.data.message).toBe(&#39;Success&#39;);<br>});</pre><h4>Snapshot Testing</h4><blockquote>Snapshot testing ensures that UI renders consistently over time. Jest captures a snapshot of the rendered component and compares it with future instances to detect any unintended changes in the component.</blockquote><p><strong><em>Creating a snapshot and comparing it</em></strong></p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react-native&#39;;<br>import Button from &#39;../components/Button&#39;;<br><br>test(&#39;Button component renders correctly&#39;, () =&gt; {<br>  //toJSON() generates a Snapshot of the component<br>  const tree = render(&lt;Button title=&quot;Click Me&quot; /&gt;).toJSON();<br><br>  //toMatchSnapshot() compares the snapshot with the previous snapshot <br>  expect(tree).toMatchSnapshot();<br>});</pre><p><strong><em>Updating Snapshot</em></strong></p><p>If any intentional UI changes occur, then you can update the snapshot using</p><pre>npm test -- -u<br>or<br>yarn test -- -u</pre><h4>File Structure for Writing Test Cases</h4><p>It is better to separate the test cases of each component or file with their parent component. It provides better readability and file tracking of the respective test case. The recommended file structure for test cases is like:</p><pre>/root-directory<br>  ├── src<br>  │   ├── components<br>  │   │   ├── Button.js<br>  │   │   ├── __tests__<br>  │   │   │   ├── Button.test.js<br>  │   ├── utils<br>  │   │   ├── helpers.js<br>  │   │   ├── __tests__<br>  │   │   │   ├── helpers.test.js<br>  │   │   ├── __mocks__<br>  │   │   │   ├── functionCall.js<br>  │   ├── screens<br>  │   │   ├── HomeScreen.js<br>  │   │   ├── __tests__<br>  │   │   │   ├── HomeScreen.test.js<br>  │   │   ├── __mocks__<br>  │   │   │   ├── axios.js</pre><h4>Running Test Cases</h4><p><em>To run all tests:</em></p><pre>npm test<br>or<br>yarn test</pre><p><em>To run a single test:</em></p><pre>npm test -- Button.test.js<br>or<br>yarn test -- Button.test.js</pre><p><em>To run tests in watch mode:</em></p><pre>npm test -- --watch<br>or<br>yarn test -- --watch</pre><p><em>To generate a coverage report:</em></p><pre>npm test -- --coverage<br>or<br>yarn test -- --coverage</pre><p>You can even add the command to <strong>package.json</strong> so you can run the test cases before extracting the <strong>apk/aab bundle</strong> or while performing any action that can probably go to production.</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;build-apk&quot;: &quot;yarn test &amp;&amp; cd android &amp;&amp; ./gradlew assembleRelease&quot;,<br>    &quot;build-aab&quot;: &quot;yarn test &amp;&amp; cd android &amp;&amp; ./gradlew bundleRelease&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fRkLjZl8qOd1pf3gxBD7w.png" /><figcaption>Response of running test cases</figcaption></figure><h4>What to Test and What Not to Using Jest</h4><p><strong>What to Test ✅</strong></p><ol><li>UI component rendering correctly</li><li>Functions and utility methods</li><li>API call responses using mocking</li><li>Navigation and state management</li><li>Async operations and promise resolutions</li></ol><p><strong>What not to Test ❌</strong></p><ol><li>Library or package integrations</li><li>Styles and visual implementations</li><li>Console logs and implementations</li><li>Native platform behaviours</li><li>Hardcoded values with no functional logic</li></ol><h3>Performance Testing</h3><blockquote>Performance testing ensures smooth performance across different devices and operating systems. This section covers Android Studio and Xcode for performance analysis.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHufug5SnbfTNj-tcf-BLw.png" /><figcaption>Performance Testing in Mobile App</figcaption></figure><h4>Android Studio (Android OS)</h4><p>Android Studio provides various tools to test CPU utilisation, battery consumption, memory leaks, GPU renders and many more. In this we will go through the tools provided by Android Studio and how to use them.</p><h4><strong>Profiler</strong></h4><p>Profiler helps analyze CPU, memory, and network activity in real time. It allows you to:</p><ol><li>Detect memory leaks and excessive memory usage</li><li>Identify slow functions causing performance drops</li><li>Monitor network requests for optimization</li></ol><figure><img alt="AndroidStudioProfiler" src="https://cdn-images-1.medium.com/max/1024/1*B5FxeiquOu5B0PXrf8os7w.png" /><figcaption>Android Studio Profiler</figcaption></figure><h4>GPU Rendering Profile</h4><p>The <strong>GPU Rendering Profile</strong> highlights frame rendering times to detect UI lag. Steps to enable it:</p><ol><li>Open <strong>Developer Options</strong> on your Android device.</li><li>Enable <strong>Profile GPU Rendering</strong>.</li><li>Select <strong>On screen as bars</strong> to visualize frame rendering time.</li><li>Green bars indicate smooth rendering; red bars highlight performance issues.</li></ol><h4>Network Throttling</h4><p>This tool simulates different network conditions to test app performance under:</p><ul><li>Slow 3G/4G networks</li><li>High latency scenarios</li><li>Packet loss situations</li></ul><p>To enable Network Link Conditioner on <strong>Android emulator:</strong></p><ol><li>Open <strong>Android Emulator Extended Controls</strong>.</li><li>Navigate to <strong>Cellular</strong>.</li><li>Adjust the network profile (e.g., Edge, 3G, LTE) to simulate different conditions.</li></ol><figure><img alt="NetworkThrottle" src="https://cdn-images-1.medium.com/max/1024/1*Hj-3unoCgem5EHIaHIp88g.jpeg" /><figcaption>Network Throttling in Android Studio</figcaption></figure><h4>Identifying UI Thread Bottlenecks</h4><p>UI thread bottlenecks occur when long-running operations block the main thread, causing UI lag. Some of the common causes of this are:</p><ul><li>Heavy computations inside render functions</li><li>Blocking API calls</li><li>Excessive re-renders due to state updates</li></ul><p>To fix this:</p><ul><li>Move expensive operations to background threads using <strong>React Native’s InteractionManager</strong></li><li>Optimize component rendering with <strong>React.memo and useCallback</strong></li><li>Reduce unnecessary re-renders with <strong>FlatList optimizations</strong></li></ul><h4>Measuring Battery Consumption</h4><p>Battery drain can occur due to background tasks, high CPU usage, or excessive network calls. Steps to analyze battery consumption:</p><ol><li>Open <strong>Android Studio Profiler</strong>.</li><li>Select <strong>Energy</strong> to monitor battery usage.</li><li>Identify components causing unnecessary power drain.</li></ol><h4>Xcode (iOS)</h4><h4>Instruments</h4><p>Instruments is a powerful tool in Xcode for analyzing app performance. It helps track CPU usage, memory consumption, and energy efficiency.</p><ul><li>Open Xcode and go to <strong>Product &gt; Profile</strong>.</li><li>Select the <strong>Instruments</strong> tool for the type of analysis you need.</li><li>Run the app and collect performance data.</li></ul><figure><img alt="XcodeProfiler" src="https://cdn-images-1.medium.com/max/1024/1*hHOuOg652A7am_Olb-N6lg.png" /><figcaption>Xcode Instruments (Profiler)</figcaption></figure><h4>Leaks Instruments</h4><p>Leaks Instruments detects memory leaks in your app, which can lead to crashes or performance degradation.</p><ul><li>Select <strong>Leaks</strong> in Instruments.</li><li>Run your app and interact with it.</li><li>Identify objects that are not getting deallocated and fix them.</li></ul><h4>Time Profiler</h4><p>Time Profiler helps identify CPU-intensive operations that slow down your app.</p><ul><li>Open Instruments and select <strong>Time Profiler</strong>.</li><li>Start recording and perform actions in your app.</li><li>Analyze the call tree to find bottlenecks and optimize performance.</li></ul><h4>Identifying UI Thread Bottlenecks</h4><p>UI thread bottlenecks occur when expensive operations block the main thread, causing janky animations and slow UI updates. To detect and fix them:</p><ul><li>Use <strong>Time Profiler</strong> to check which functions are running on the main thread.</li><li>Move expensive operations to background threads using <strong>GCD (Grand Central Dispatch)</strong>.</li><li>Use <strong>Core Animation Instrument</strong> to monitor smooth rendering of UI components.</li></ul><h4>Measuring Battery Consumption</h4><p>Battery drain is a critical issue in mobile apps. To analyze battery consumption:</p><ul><li>Use <strong>Energy Log Instrument</strong> in Instruments.</li><li>Monitor CPU, network activity, and background tasks.</li><li>Reduce unnecessary background updates and optimize network requests.</li></ul><p>In this article, we explored the importance of testing in Mobile applications and how to effectively implement test scripts using <strong>Jest</strong>. By thoroughly testing your app before releasing it to production, you can ensure a high-quality user experience, minimize bugs, and enhance app performance. A well-tested app not only improves reliability but also builds <strong>user trust and loyalty</strong>.</p><p>However, testing alone is not enough — <strong>security</strong> is also a top priority. Users trust apps that prioritize their privacy and data protection. To add extra layers of security to your React Native application, refer to my detailed guide: <a href="https://medium.com/@ankit.ad.dhawan/secure-your-react-native-app-from-vulnerabilities-e23b5cb00b2a"><strong>Secure Your React Native Application from Vulnerabilities</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce96f75f0946" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Accounts in React Native]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/multiple-accounts-in-react-native-9144751a98d8?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/9144751a98d8</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[multiple-accounts]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 12:30:48 GMT</pubDate>
            <atom:updated>2025-01-26T12:30:48.316Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s mobile application era, Using multiple accounts has become a common feature. Users often have different needs for multiple accounts within the same app. For example, a social media app where they can use one account for personal use and another for professional marketing. An email app where they can use personal and work email within the same application. The ability to switch between these accounts seamlessly enhances the user experience.</p><p>However, implementing multiple-account support isn’t straightforward. Developers need to ensure that the data for each account remains isolated while giving easy access to switch between them. This approach requires a robust state management solution such as Redux which can handle this type of situation. By dynamically creating a store for each account, we can achieve the isolation of data while using the same reducer for all accounts.</p><p>In this article, we’ll learn how Redux can create a robust architecture for handling multiple accounts in a single app. We’ll walk through the code implementation for creating, switching and deleting a store and using it with a single reusable reducer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_0hyysjFHjb18fTDbn3Ew.png" /><figcaption>Multiple Accounts in Mobile Applications</figcaption></figure><h3>What is Redux and how does it work?</h3><blockquote>Redux is a powerful and predictable state management library widely used in modern application development. It centralizes the state of your app in a single store, which is responsible for storing the entire state tree.</blockquote><p>In a multi-account setup, each account operates with its own independent Redux store. However, you don’t need to write separate reducers for each store. Instead, you can use a single reusable reducer that handles the same set of actions for all stores. The key difference is that each store will be differentiated with a unique identifier (e.g. Account ID), ensuring that the state is completely isolated for each account.</p><blockquote>Here’s how it works:</blockquote><blockquote><strong>Reusable Reducer:</strong> The reducer logic remains the same regardless of the account. For example, if you have a userReducer to handle all the user-related actions, it can be used across all the stores.</blockquote><blockquote><strong>Store Creation:</strong> Each account gets its own store, created dynamically via a function (e.g. createStoreForAccount). The reducer is passed to the store during creation.</blockquote><pre>let stores = {};<br>let activeStore = null;<br><br>const createStoreForAccount = (accountId) =&gt; {<br>  const persistConfig = {<br>    key: accountId, // Pass the unique identifier for your store<br>    storage: AsyncStorage,<br>  };<br><br>  const persistedReducer = persistReducer(persistConfig, createRootReducer());<br><br>  const store = configureStore({<br>    reducer: persistedReducer,<br>    middleware: (getDefaultMiddleware) =&gt; getDefaultMiddleware(),<br>  });<br><br>  const persistor = persistStore(store);<br><br>  stores[accountId] = { store, persistor };<br>  return stores[accountId];<br>};</pre><h4>Why do we need to have a unique identifier?</h4><blockquote>The unique identifier acts as a key to identify each store. The key is stored in the device’s local storage (e.g. Async Storage) to ensure that it remains persistent across the session, the data remains isolated for each account and provides quick switching for accounts.</blockquote><h4>How same reducer is used for each store?</h4><blockquote>The reducer actions remain the same for each store; the only difference is the scope of each store, which is determined by the unique key. The reducer is given to each store at the time of creation. Each action taken on the reducer will stay respective to the unique identifier we have provided to the store.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_7cVA6uDP_CnBUsMRa3kw.png" /><figcaption>Redux working for Multiple Accounts</figcaption></figure><h3>Redux Store Switching</h3><p>Store switching is the most critical part of multiple account applications for ensuring that the store gets switched without data being compromised between two stores. The goal of store switching is to load the appropriate redux store dynamically based on the selected account’s unique key, ensuring smooth account switching without data overlap. Store switching is achieved by dynamically updating the active Redux store based on the account ID (or key).</p><pre>let stores = {};<br>let activeStore = null;<br><br>export const switchStore = (accountId) =&gt; {<br>  // Check if the store for the account exists<br>  if (!stores[accountId]) {<br>    console.error(`Store for account ${accountId} does not exist.`);<br>    return null;<br>  }<br><br>  activeStore = stores[accountId];<br>  activeStore.persistor.persist();<br><br>  return activeStore;<br>};</pre><p>You will also need to make a store wrapper that will handle the store switches from the root component of the App.</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br>import { switchStore, createStoreForAccount } from &#39;./store&#39;;<br><br>const StoreContext = createContext();<br><br>export const StoreProvider = ({ children }) =&gt; {<br>  const [currentStore, setCurrentStore] = useState(() =&gt; createStoreForAccount(&#39;root&#39;));<br><br>  const handleSwitchAccount = (accountId) =&gt; {<br>    console.log(`Switching to account: ${accountId}`);<br>    const newStore = switchStore(accountId);<br>    if (newStore) {<br>      setCurrentStore(newStore);<br>    } else {<br>      console.error(`Failed to switch store for account: ${accountId}`);<br>    }<br>  };<br><br>  return (<br>    &lt;StoreContext.Provider value={{ currentStore, switchAccount: handleSwitchAccount }}&gt;<br>      {children}<br>    &lt;/StoreContext.Provider&gt;<br>  );<br>};<br><br>export const useStoreContext = () =&gt; useContext(StoreContext);</pre><p>Now, we add the store wrapper to our Root file just like any other store wrapper component.</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import { PersistGate } from &#39;redux-persist/integration/react&#39;;<br>import { StoreProvider, useStoreContext } from &#39;./redux/storeprovider&#39;;<br>import AppNavigator from &#39;./navigator&#39;;<br><br>const App = () =&gt; (<br>  &lt;StoreProvider&gt;<br>    &lt;MainApp /&gt;<br>  &lt;/StoreProvider&gt;<br>);<br><br>const MainApp = () =&gt; {<br>  const { currentStore, switchAccount } = useStoreContext();<br><br>  const handleAccountSwitch = (newAccountId) =&gt; {<br>    switchAccount(newAccountId);<br>  };<br><br>  return (<br>    &lt;Provider store={currentStore.store}&gt;<br>      &lt;PersistGate loading={null} persistor={currentStore.persistor}&gt;<br>        &lt;AppNavigator handleSwitchAccount={handleAccountSwitch} /&gt;<br>      &lt;/PersistGate&gt;<br>    &lt;/Provider&gt;<br>  );<br>};<br><br>export default App;</pre><h4>How does store switching work in this approach?</h4><ol><li>The user initiates the store switching by clicking on any of the accounts in the UI.</li><li>The switchStore function receives the unique identifier and switches the store if exists or creates a new one if it doesn’t exist.</li><li>The switchStore function updates the activeStore in the parent store wrapper which is reflected on the whole app at once.</li></ol><p>This implementation ensures that the data overlapping will not happen and data will stay isolated. This also lets users switch between accounts efficiently and quickly without app refreshing or session reloading.</p><h4>Switching Accounts from anywhere in the project</h4><p>In the previous paragraph, we learned about the technical approach to switching stores and how it works, but how can we switch stores in the UI or anywhere from the app?</p><p>Switching accounts involves using the <strong><em>useStoreContext()</em></strong> from the store provider. This context provides the necessary function and state to manage and switch stores dynamically. It provides a shared context that is responsible for maintaining the active store across the app.</p><p>Here’s how you can switch to any account from the app using <strong><em>useStoreContext()</em></strong></p><pre>import React from &#39;react&#39;;<br>import { Button } from &#39;react-native&#39;;<br>import { useStoreContext } from &#39;./redux/storeprovider&#39;;<br><br>const SwitchAccountButton = () =&gt; {<br>  const { switchAccount } = useStoreContext();<br><br>  const handleSwitchAccount = async () =&gt; {<br>    const accountId = &#39;user456&#39;; // The unique identifier for the store<br><br>    try {<br>      await switchAccount(accountId);<br>      console.log(`Switched to account: ${accountId}`);<br>    } catch (error) {<br>      console.error(`Failed to switch account: ${error.message}`);<br>    }<br>  };<br><br>  return &lt;Button title=&quot;Switch Account&quot; onPress={handleSwitchAccount} /&gt;;<br>};<br><br>export default SwitchAccountButton;</pre><h4>Why can’t we use switchStore() function directly?</h4><p>It is technically possible to switch stores directly from the store instead of using useStoreContext() but it is not recommended because of several reasons. useStoreContext() ensures proper state management, seamless integration and scalability. Here are several reasons why you should use a store context.</p><ol><li>Automatically manages and updates the app’s state.</li><li>Centralizes logic in a single place for reusability.</li><li>Ensures consistent state management across the app.</li><li>Centralized error handling.</li><li>Ensures component renderer properly by leveraging React’s context.</li></ol><h3>Deleting a Redux Store</h3><p>Deleting a store in a multi-account application is essential if a user wishes to delete their account from the application. This process involves the purging of the persisted state and removing it from the memory to free up resources and accidental store creation. Additionally, the unique identifiers should be removed from the places where they are stored to ensure a complete cleanup.</p><pre>let stores = {};<br>let activeStore = null;<br><br>export const deleteStore = (accountId) =&gt; {<br>  if (stores[accountId]) {<br>    stores[accountId].persistor.purge(); // Clear persisted state<br>    delete stores[accountId];<br>    console.log(&quot;Store deleted: &quot;, accountId)<br>  }<br>};</pre><h4>Why is Store deletion important?</h4><ol><li>Give users complete access to their personal data.</li><li>Data cleanup</li><li>Proper Account Management</li></ol><p>Multiple account management in today’s era of mobile applications is not just a necessity but a leverage to user experience. By properly using Redux stores and implementing multi-store architecture, developers can create scalable and efficient solutions for applications that require multiple account management. In this article, we also learnt how we can achieve the same by dynamically creating a store using a unique identifier, switching between stores and deleting the store if the user wishes to delete their account from the application.</p><p>However, with great flexibility comes the responsibility of ensuring the security of the user data. When handling multiple account data, it is crucial to safeguard sensitive information and make transactions from your applications securely to your server. For a detailed guide on how you can secure your react native app from various vulnerabilities, you can refer to my article: <a href="https://medium.com/@ankit.ad.dhawan/secure-your-react-native-app-from-vulnerabilities-e23b5cb00b2a">Secure your React Native Application from Vulnerabilities</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9144751a98d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Your React Native App from Vulnerabilities]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/secure-your-react-native-app-from-vulnerabilities-e23b5cb00b2a?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23b5cb00b2a</guid>
            <category><![CDATA[app-security]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 19:02:35 GMT</pubDate>
            <atom:updated>2024-11-24T19:02:35.114Z</atom:updated>
            <content:encoded><![CDATA[<p>From the start, mobile app development has often been about creating user interfaces, seamless navigation, smooth animations, and efficient API integration. These are the aspects that grab attention and define the user experience. However, when deploying apps at a production level, <strong>app security becomes a critical focus</strong> — which every developer must prioritise.</p><p>Your app becomes threats like reverse engineering, and frontend attacks without proper security measures. These vulnerabilities can expose sensitive information, compromise your app’s functionality, and damage user trust. Just as great UI design makes an app delightful, robust security ensures it’s safe.</p><p>In a production environment, security isn’t optional. It’s a shield that protects your app and its users from malicious activities. Addressing this early on, alongside features and design, is essential to building apps that are functional, and beautiful but also secure, and reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5xWO5m5Eh8vBpH59GnkzXA.jpeg" /><figcaption>React Native App Security</figcaption></figure><p>This article dives into the mostly known attacks on React Native apps and shows you how to stop them. From preventing reverse engineering to securing data and network communication, you’ll learn actionable ways to fortify your app and keep it safe.</p><h3>Jail Broken / Rooted devices</h3><blockquote>Jailbroken (iOS) and rooted (Android) devices bypass system security, exposing sensitive app data, allowing app tampering, and enabling unauthorized actions like bypassing in-app purchases. This compromises both user data and app integrity.</blockquote><p>Prevent your app from running on compromised devices by using the <a href="https://www.npmjs.com/package/jail-monkey">jail-monkey</a> package in React Native. It detects jailbroken/rooted devices and allows you to disable app functionality or show a warning.</p><pre>import JailMonkey from &#39;jail-monkey&#39;;<br><br>if (JailMonkey.isJailBroken()) {<br>    // This function will detect jailbroken devices for iOS<br>    // and rooted devices for Android<br>    alert(&#39;This app cannot run on jailbroken or rooted devices.&#39;);<br>    // Perform your action to dismiss the app and block certain actions<br>}</pre><h3>Insecure Local Storage</h3><blockquote>Local storage in React Native is often used to store sensitive data like authentication tokens, user details, and session information for persistent use. However, if this data is stored insecurely, it becomes vulnerable. Hackers with physical access to a device or through tools on rooted/jailbroken devices can easily access and extract this data. They can use debugging tools or file system access to read the stored data, potentially stealing user credentials, impersonating users, or modifying app functionality. This compromises both user privacy and app security.</blockquote><p>You should prefer to use updated secure storage instead of outdated and insecure local storage. Secure storages encrypt the data you store in your local storage.</p><ol><li><strong>Insecure Storage</strong><br>Async Storage, Android Shared Preferences, Environment variables</li><li><strong>Secure Storage<br></strong>iOS keychain, Android keystore, Android Secure Shared Preferences</li></ol><h3>SSL Pinning</h3><blockquote>SSL pinning is a security technique that ensures an app only communicates with trusted servers by validating the server’s SSL certificate against a predefined list or public key. Without SSL pinning, attackers can intercept data through Man-in-the-Middle (MitM) attacks by impersonating the server and using fraud certificates. This can expose sensitive information, such as user credentials or financial details. SSL pinning is crucial because it prevents such attacks by ensuring that communication is always encrypted and verified, protecting both user data and the integrity of the app’s connection to trusted servers.</blockquote><p>SSL Pinning can be implemented in native code by adding the SHA256 pin and the URL of your trusted server to which your app is supposed to communicate.</p><p><strong>SSL Pinning in Android<br></strong>To add SSL pinning in Android, you will need to create a file in the folder <em>android/app/src/main/res/xml </em>named <a href="https://www.npmjs.com/package/jail-monkey">n</a>etwork_security_config.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;network-security-config&gt;<br>    &lt;domain-config cleartextTrafficPermitted=&quot;true&quot;&gt;<br>        &lt;domain includeSubdomains=&quot;true&quot;&gt;myserverurl.com&lt;/domain&gt;<br>        &lt;pin-set expiration=&quot;2025-12-01&quot;&gt;<br>            &lt;pin digest=&quot;SHA-256&quot;&gt;[INSERT SHA256 PIN HERE]=&lt;/pin&gt;<br>        &lt;/pin-set&gt;<br>    &lt;/domain-config&gt;<br>&lt;/network-security-config&gt;</pre><p>Now, in AndroidManifest.xml add this line</p><pre>    &lt;application<br>      android:name=&quot;.MainApplication&quot;<br>      android:label=&quot;@string/app_name&quot;<br>      android:icon=&quot;@mipmap/ic_launcher&quot;<br>      android:usesCleartextTraffic=&quot;true&quot;<br>      android:networkSecurityConfig=&quot;@xml/network_security_config&quot; //ADD THIS LINE<br>      &lt;!-- REST OF YOUR CODE --&gt;</pre><p><strong>SSL Pinning in iOS<br></strong>To add SSL Pinning in iOS, we’ll use TrustKit which is an open-source framework used to add SSL pinning in iOS. For this, we’ll only need to add a few lines of code in AppDelegate.m</p><pre>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br>{<br><br>  NSDictionary *trustKitConfig =<br>  @{<br>    kTSKSwizzleNetworkDelegates: @YES,<br>    kTSKPinnedDomains: @{<br>        @&quot;myserverurl.com&quot; : @{<br>            kTSKIncludeSubdomains: @YES,<br>            kTSKEnforcePinning: @YES,<br>            kTSKDisableDefaultReportUri: @YES,<br>            kTSKPublicKeyHashes : @[<br>                  @&quot;[INSERT YOUR SHA256 PIN HERE]&quot;, //primary key<br>                  @&quot;[INSERT YOUR SHA256 BACKUP PIN HERE]&quot; //backup key<br>            ],<br>        },<br>    }};<br>  [TrustKit initSharedInstanceWithConfiguration:trustKitConfig];<br>  //REST OF THE CODE<br>}</pre><h3>ClearTextTraffic</h3><blockquote><strong>ClearTextTraffic</strong> refers to unencrypted HTTP traffic, which sends data in plain text, making it vulnerable to interception and manipulation by attackers, especially on unsecured networks like public Wi-Fi. If <strong>ClearTextTraffic</strong> is allowed, sensitive information such as passwords, personal data, or session tokens can be exposed, putting the app and users at risk of data breaches or man-in-the-middle attacks.</blockquote><p>It’s essential to set <strong>ClearTextTraffic</strong> to false in AndroidManifest.xml to ensure that all communication is encrypted using HTTPS, protecting data from interception and ensuring the app&#39;s security over networks.</p><h3>Code Obfuscation</h3><blockquote>Code Obfuscation is a method that makes the code hard to read, reverse engineering, and enhances mobile app security.</blockquote><p>React Native creates a bridge between JavaScript and Native Code so there are several ways to obfuscate the native code in your React Native app.</p><ul><li><strong>Proguard: </strong>It is an open-source tool in Android SDK to obfuscate your Java code</li><li><strong>Hermes: </strong>It is a JavaScript engine developed by Facebook to obfuscate JavaScript code in the React Native app.</li><li><strong>ixGuard: </strong>It is an obfuscator used to Obfuscate Swift code in iOS apps.</li></ul><h3>Stack Smashing</h3><blockquote>It is a security vulnerability performed by hackers to perform Buffer overflow by adding malicious code to the device forcing the app to misbehave and causing the app to crash.</blockquote><p>To prevent such type of attack in iOS we need to enable Stack canary protection in an iOS app.</p><ul><li>In Xcode, select your target in the “Targets” section, then click the “Build Settings” tab to view the target’s settings</li><li>Make sure that the “-fstack-protector-all” option is selected in the “Other C Flags” section</li><li>Make sure that Position Independent Executables (PIE) support is enabled</li></ul><h3>Weak Navigation System</h3><blockquote>A weak navigation system in a React Native app can compromise security by allowing unauthorized access to restricted screens or actions. Suppose the app’s navigation is not properly secured. In that case, users can bypass authentication or access sensitive data by manipulating the navigation stack or URLs, leading to potential data leaks or misuse of app functionality.</blockquote><p>To prevent this, it’s essential to implement robust navigation controls by ensuring that sensitive screens are protected with authentication checks and that navigation routes are properly validated. Using libraries like react-navigation with guards, and managing state-based access control, helps prevent unauthorized navigation and strengthens app security.</p><h3>Disable Logs</h3><blockquote>Disabling logs in a React Native app is crucial for security because logs can inadvertently expose sensitive information, such as user data, authentication tokens, or error details, which attackers can access. If logs are not disabled or properly managed in production, they may provide valuable insights for malicious users to exploit vulnerabilities or tamper with the app. Therefore, turning off or restricting logging in production environments helps prevent the accidental exposure of sensitive data and protects the app from potential security breaches.</blockquote><p>While releasing the code to production you can add a line in the root file of the app to disable all the app logs.</p><pre>console.log(() =&gt; {})</pre><h3>Mock Location</h3><blockquote>A mock location is a developer tool in Android that allows users to simulate GPS locations for testing purposes. However, malicious users can exploit it to spoof their location which can mislead location-based services or manipulate app behavior for geolocation services.</blockquote><p>To prevent Mock Location on your app you can create a native function in the Android app and create a native bridge to detect Mock Location in your React native app</p><pre>package com.example.yourpackage;<br><br>import android.content.Context;<br>import android.location.Criteria;<br>import android.location.Location;<br>import android.location.LocationListener;<br>import android.location.LocationManager;<br>import android.os.Build;<br>import android.os.Bundle;<br>import androidx.annotation.NonNull;<br>import com.facebook.react.bridge.ReactApplicationContext;<br>import com.facebook.react.bridge.ReactContextBaseJavaModule;<br>import com.facebook.react.bridge.ReactMethod;<br>import com.facebook.react.bridge.Promise;<br><br>public class MockLocationDetector extends ReactContextBaseJavaModule {<br><br>    private final ReactApplicationContext reactContext;<br><br>    public MockLocationDetector(ReactApplicationContext reactContext) {<br>        super(reactContext);<br>        this.reactContext = reactContext;<br>    }<br><br>    @NonNull<br>    @Override<br>    public String getName() {<br>        return &quot;MockLocationDetector&quot;;<br>    }<br><br>    @ReactMethod<br>    public void isMockLocationEnabled(final Promise promise) {<br>        final LocationManager locationManager = (LocationManager) reactContext.getSystemService(Context.LOCATION_SERVICE);<br><br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN_MR2) {<br>            try {<br>                Criteria criteria = new Criteria();<br>                criteria.setAccuracy(Criteria.ACCURACY_FINE);<br><br>                locationManager.requestSingleUpdate(criteria, new LocationListener() {<br>                    @Override<br>                    public void onLocationChanged(Location location) {<br>                        boolean isMockLocation = location != null &amp;&amp; location.isFromMockProvider();<br>                        promise.resolve(isMockLocation);<br>                    }<br><br>                    @Override<br>                    public void onStatusChanged(String provider, int status, Bundle extras) {}<br><br>                    @Override<br>                    public void onProviderEnabled(String provider) {}<br><br>                    @Override<br>                    public void onProviderDisabled(String provider) {}<br>                }, null);<br><br>            } catch (SecurityException e) {<br>                promise.reject(&quot;LOCATION_PERMISSION_DENIED&quot;, &quot;Location permission is denied&quot;);<br>            }<br>        } else {<br>            promise.resolve(false); // For devices below Jelly Bean MR2, mock location detection is not supported<br>        }<br>    }<br>}</pre><h3>Outdated / Deprecated Dependencies</h3><blockquote>Outdated and deprecated dependencies in a React Native app can pose significant security risks because they may contain unpatched vulnerabilities that attackers can exploit. As libraries and packages evolve, newer versions fix security issues and improve performance. If an app relies on outdated or deprecated dependencies, it becomes susceptible to known exploits, compromising data integrity, user privacy, and overall app security.</blockquote><p>You should regularly update the packages that your app is using and should always avoid outdated dependencies. You can check the outdated packages in your app by using npm command.</p><pre>npm outdated</pre><p>In conclusion, securing your React Native app is essential to protect both your users and your app from potential threats. By prioritizing security practices throughout development and ensuring you stay ahead of emerging risks, you build trust with your users and safeguard their data. Security is an ongoing commitment, and by adopting the right measures, you ensure your app remains reliable, safe, and resilient in the face of evolving challenges. Ultimately, a secure app not only enhances user experience but also strengthens your app’s reputation and success. Remember, a secure app is a successful app!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23b5cb00b2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Dynamic Island widget using React Native]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/first-step-towards-creating-a-dynamic-island-widget-using-react-native-e6877a3fad52?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6877a3fad52</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[dynamic-island]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[live-activities]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 17:15:26 GMT</pubDate>
            <atom:updated>2023-10-18T17:17:37.848Z</atom:updated>
            <content:encoded><![CDATA[<p>Dynamic Island launched in 2022 by Apple in iPhone 14 Pro and newer devices is an innovative integration of software functions which lets us see the live activities from various applications and sources. Live Activities provides an interactive way to see the updates from applications on the newly launched Dynamic Island.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1i3pw3p-gAjwhA54VTtJg.png" /></figure><p>Now Developers can add support for Dynamic Island using Activity Kit Framework in xcode.</p><blockquote>What is the Activity Kit Framework?</blockquote><blockquote>Activity Kit Framework gives the support to share the live status of your application to Dynamic Island or Lock Screen</blockquote><p>React Native developers can also integrate a Dynamic Island widget by creating a native Bridge between iOS and react native applications. Using Native Bridge you can have your app communicate with the Swift code written in the iOS app.</p><p>So let’s start with building your first Dynamic Island Widget using React native.</p><h4>Step 1</h4><p>Open your terminal and create a new React native project using this command</p><pre>npx react-native init [YOUR-PROJECT-NAME]</pre><h4>Step 2</h4><p>Now open the xcworkspace file in your ios directory of the project that you just created and go to the info panel on top.</p><p>In Custom iOS Target Properties add a new property ‘NSSupportsLiveActivities’ and change the value to YES. This will enable the live activities in your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdRkd5T9er99VPxzIXGd1A.png" /></figure><h4>Step 3</h4><p>Create 2 Swift files in your ios project from xcode and name them ‘LiveActivityModule’ &amp; ‘LiveActivityModuleHeader’</p><p>In LiveActivityModule add your Native function</p><pre>import Foundation<br><br>@objc(LiveActivity)<br>class LiveActivity: NSObject {<br>  <br>  func startActivity() {<br>    print(&quot;Hello World!&quot;)<br>  }<br>}</pre><p>In LiveActivityModuleHeader write the code that will communicate with your React native application</p><pre>#import &lt;React/RCTBridgeModule.h&gt;<br><br>@interface RCT_EXTERN_MODULE(LiveActivity, NSObject)<br><br>RCT_EXTERN_METHOD(startActivity)<br>  <br>@end</pre><p>This code will let our React native application communicate with native iOS code</p><h4>Step 4</h4><p>Open App.js in your react native project and add this code to run the Native method.</p><pre>import React from &#39;react&#39;;<br>import { Button, NativeModules } from &#39;react-native&#39;;<br><br>const { LiveActivity } = NativeModules;<br><br>const App = () =&gt; {<br><br>  const onStartActivity = () =&gt; {<br>    LiveActivity.startActivity();<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Button title=&quot;Start Activity&quot; onPress={onStartActivity} /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default App;</pre><p>If you did everything right then on pressing the ‘Start Activity’ button, you should be able to “Hello World!” in logs on xcode. This means that your native code is integrated with the React native application.</p><h4>Step 5</h4><p>To create a Dynamic Island widget you need to follow few steps:</p><ol><li>In xcode, go to File then New then Target</li><li>Search for ‘Widget Extension’ and click Next</li><li>Give your widget a name and make sure ‘Include Live Activity’ is checked before clicking Finish.</li><li>A separate folder will be created for the widget with pre-written swift code. Open the file named ‘[YOUR-WIDGET-NAMELiveActivity]’ and replace the content of the file with this</li></ol><pre>import ActivityKit<br>import WidgetKit<br>import SwiftUI<br><br>struct LiveActivityAttributes: ActivityAttributes {<br>    public struct ContentState: Codable, Hashable {<br>        // Dynamic stateful properties about your activity go here!<br>    }<br><br>    // Fixed non-changing properties about your activity go here!<br>    var name: String<br>}<br><br>struct LiveActivityLiveActivity: Widget {<br>    var body: some WidgetConfiguration {<br>        ActivityConfiguration(for: LiveActivityAttributes.self) { context in<br>            // Lock screen/banner UI goes here<br>            VStack {<br>                Text(&quot;Hello&quot;)<br>            }<br>            .activityBackgroundTint(Color.cyan)<br>            .activitySystemActionForegroundColor(Color.black)<br><br>        } dynamicIsland: { context in<br>            DynamicIsland {<br>                // Expanded UI goes here.  Compose the expanded UI through<br>                // various regions, like leading/trailing/center/bottom<br>                DynamicIslandExpandedRegion(.leading) {<br>                    Text(&quot;Left&quot;)<br>                }<br>                DynamicIslandExpandedRegion(.trailing) {<br>                    Text(&quot;Right&quot;)<br>                }<br>                DynamicIslandExpandedRegion(.bottom) {<br>                    Text(&quot;Bottom Content&quot;)<br>                    // more content<br>                }<br>            } compactLeading: {<br>                Text(&quot;L&quot;)<br>            } compactTrailing: {<br>                Text(&quot;R&quot;)<br>            } minimal: {<br>                Text(&quot;Min&quot;)<br>            }<br>            .widgetURL(URL(string: &quot;http://www.apple.com&quot;))<br>            .keylineTint(Color.red)<br>        }<br>    }<br>}</pre><p>This code can be edited to design your Dynamic Island widget in both collapsed and expanded.</p><p>5. Now go back to your Native Module code and make changes in your startActivity function</p><pre>  @objc(startActivity)<br>  func startActivity() {<br>    do{<br>      if #available(iOS 16.1, *){<br>        let liveActivityAttributes = LiveActivityAttributes(name: &quot;Live Activity&quot;)<br>        let liveActivityContentState = LiveActivityAttributes.ContentState()<br>        let activity = try Activity&lt;LiveActivityAttributes&gt;.request(attributes: liveActivityAttributes, contentState: liveActivityContentState,  pushType: nil)<br>        <br>      }else{<br>        print(&quot;Dynamic Island and live activies not supported&quot;)<br>      }<br>      <br>    }catch (_){<br>      print(&quot;there is some error&quot;)<br>    }<br>  }</pre><p>6. Now restart the application -&gt; Click on Start Activity and you should see the Dynamic Island running on your iOS device.</p><blockquote>Make sure you only run the application on iPhone 14 Pro or newer devices</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hSy_GUgJjrwyzdoN8PlO9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*t9TBzQ6OWeb3czgFSjv_EA.png" /></figure><h3>Updating Content in Dynamic Island</h3><p>You can update the contents of your Dynamic Island widget from your react native app.</p><p>To Update the content of the widget you need to make changes in your widget.</p><pre>import ActivityKit<br>import WidgetKit<br>import SwiftUI<br><br>struct LiveActivityAttributes: ActivityAttributes {<br>    public struct ContentState: Codable, Hashable {<br>        // Dynamic stateful properties about your activity go here!<br>        var leftName: String //ADD THIS LINE<br>    }<br><br>    // Fixed non-changing properties about your activity go here!<br>    var name: String<br>}<br><br>struct LiveActivityLiveActivity: Widget {<br>    var body: some WidgetConfiguration {<br>        ActivityConfiguration(for: LiveActivityAttributes.self) { context in<br>            // Lock screen/banner UI goes here<br>            VStack {<br>                Text(&quot;Hello&quot;)<br>            }<br>            .activityBackgroundTint(Color.cyan)<br>            .activitySystemActionForegroundColor(Color.black)<br><br>        } dynamicIsland: { context in<br>            DynamicIsland {<br>                // Expanded UI goes here.  Compose the expanded UI through<br>                // various regions, like leading/trailing/center/bottom<br>                DynamicIslandExpandedRegion(.leading) {<br>                      Text(context.state.leftName) //CHANGE THIS LINE<br>                }<br>                DynamicIslandExpandedRegion(.trailing) {<br>                    Text(&quot;Right)<br>                }<br>                DynamicIslandExpandedRegion(.bottom) {<br>                    Text(&quot;Bottom Content&quot;)<br>                    // more content<br>                }<br>            } compactLeading: {<br>                Text(&quot;L&quot;)<br>            } compactTrailing: {<br>                Text(&quot;R&quot;)<br>            } minimal: {<br>                Text(&quot;Min&quot;)<br>            }<br>            .widgetURL(URL(string: &quot;http://www.apple.com&quot;))<br>            .keylineTint(Color.red)<br>        }<br>    }<br>}</pre><p>Add one more function to the Module file and Module Header</p><p>Native Module File</p><pre>  @objc(updateActivity:)<br>  func updateActivity(name: String){<br>    do{<br>      if #available(iOS 16.1, *){<br>        let liveActivityContentState = LiveActivityAttributes.ContentState(leftName: name)<br>        Task{<br>          for activity in Activity&lt;LiveActivityAttributes&gt;.activities {<br>            await activity.update(using: liveActivityContentState)<br>          }<br>        }<br>      }<br>    }catch(_){<br>      print(&quot;some error&quot;)<br>    }<br>  }</pre><p>Module Header File</p><pre>#import &lt;React/RCTBridgeModule.h&gt;<br><br>@interface RCT_EXTERN_MODULE(LiveActivity, NSObject)<br><br>RCT_EXTERN_METHOD(startActivity)<br>RCT_EXTERN_METHOD(updateActivity: (NSString *) name)<br>  <br>@end</pre><p>Add a new Button in App.js for updating the content</p><pre>import React from &#39;react&#39;;<br>import { Button, NativeModules } from &#39;react-native&#39;;<br><br>const { LiveActivity } = NativeModules;<br><br>const App = () =&gt; {<br><br>  const onStartActivity = () =&gt; {<br>    LiveActivity.startActivity();<br>  };<br><br>  const onUpdateActivity = () =&gt; {<br>    LiveActivity.updateActivity(&#39;Updated Activity&#39;);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Button title=&quot;Start Activity&quot; onPress={onStartActivity} /&gt;<br>      &lt;Button title=&quot;Update Activity&quot; onPress={onUpdateActivity} /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default App;</pre><p>Now on clicking the Update Activity, you will see the content updated on your widget</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Q-hGBDJKU7vOr-d0_IFkZg.png" /></figure><h3>Ending Dynamic Island Activity</h3><p>Just like you started the activity from your React native app, you can also end the Live Activity from it.</p><p>To end the Live Activity make a new function in Module and Module Header file.</p><pre>  @objc(endActivity)<br>   func endActivity(){<br>     Task{<br>       for activity in Activity&lt;LiveActivityAttributes&gt;.activities {<br>         await activity.end()<br>       }<br>     }<br>   }</pre><pre>#import &lt;React/RCTBridgeModule.h&gt;<br><br>@interface RCT_EXTERN_MODULE(LiveActivity, NSObject)<br><br>RCT_EXTERN_METHOD(startActivity)<br>RCT_EXTERN_METHOD(updateActivity: (NSString *) name)<br>RCT_EXTERN_METHOD(endActivity)<br>  <br>@end</pre><p>And in your React native code, add a new button to end the activity</p><pre>import React from &#39;react&#39;;<br>import { Button, NativeModules } from &#39;react-native&#39;;<br><br>const { LiveActivity } = NativeModules;<br><br>const App = () =&gt; {<br><br>  const onStartActivity = () =&gt; {<br>    LiveActivity.startActivity();<br>  };<br><br>  const onUpdateActivity = () =&gt; {<br>    LiveActivity.updateActivity(&#39;Updated Activity&#39;);<br>  };<br><br>  const onEndActivity = () =&gt; {<br>    LiveActivity.endActivity();<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Button title=&quot;Start Activity&quot; onPress={onStartActivity} /&gt;<br>      &lt;Button title=&quot;Update Activity&quot; onPress={onUpdateActivity} /&gt;<br>      &lt;Button title=&quot;End Activity&quot; onPress={onEndActivity} /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default App;</pre><p>Now when you click the ‘End Activity’ button the live activity on your Dynamic Island widget will stop.</p><p>Voila! You just created your first Dynamic Island widget. You can now customise the widget and add your own component to it as per your requirements.</p><p>View the <a href="https://github.com/ad-dhawan/rn-dynamic-island">source code</a> here</p><p>Thanks for giving your time 😄</p><p>References:<br><a href="https://developer.apple.com/documentation/ActivityKit">https://developer.apple.com/documentation/ActivityKit</a><br><a href="https://developer.apple.com/documentation/widgetkit/dynamicisland">https://developer.apple.com/documentation/widgetkit/dynamicisland</a><br><a href="https://reactnative.dev/docs/getting-started">https://reactnative.dev/docs/getting-started</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6877a3fad52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing API Development with GraphQL]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/revolutionizing-api-development-with-graphql-a5c582559a3f?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c582559a3f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 11:42:36 GMT</pubDate>
            <atom:updated>2023-01-04T11:42:36.917Z</atom:updated>
            <content:encoded><![CDATA[<p>GraphQL is a query language for your API that allows clients to request exactly the data they need, and nothing more. It was developed and open-sourced by Facebook and is often used as an alternative to REST APIs. With GraphQL, clients can specify exactly what data they need, and the server will return only that data, reducing the amount of data transferred and improving the efficiency of the API.</p><p>One of the main benefits of GraphQL is its flexibility. With GraphQL, clients have complete control over the data they receive and can request exactly what they need. This allows clients to be more flexible and adaptable and reduces the need for server-side changes to accommodate changes in client requirements. For example, if a client needs to access data from multiple endpoints, it can do so in a single GraphQL query, rather than making multiple HTTP requests to different endpoints.</p><p>Another benefit of GraphQL is its efficiency. Because clients can request only the data they need, the amount of data transferred is reduced, improving the efficiency of the API. This can be particularly beneficial when clients need to access multiple endpoints or the server has limited resources.</p><p>GraphQL also has a built-in type system that allows the server to describe the data it exposes, making it easier for clients to understand and consume the API. This strong typing can help to prevent errors and improve the reliability of the API.</p><p>In addition to these benefits, GraphQL has a large and active community, with a wealth of resources and tools available to support its use. Many libraries and frameworks are available for building GraphQL servers and clients, making it easy to get started with GraphQL.</p><p>Despite these benefits, there are also situations where GraphQL may not be the best choice. For example, if your API has a large number of endpoints and a complex schema, implementing GraphQL may require a significant amount of work. In such cases, it may be more efficient to use a traditional REST API.</p><p>Similarly, a traditional REST API may be more appropriate if your API has a small number of clients that are tightly coupled to the server-side implementation. With GraphQL, the clients have more control over the data they receive, which may not be desirable in all cases.</p><p>Overall, GraphQL is a powerful tool that can improve the flexibility and efficiency of your API. It is particularly well-suited for situations where clients need to access a large number of endpoints or where the server has limited resources. However, it may not be the best choice in all cases, and it is important to carefully consider the specific needs and requirements of your project before deciding whether to use GraphQL or a traditional REST API.</p><p>For example, consider a social media platform with a traditional REST API that exposes endpoints for retrieving user profiles, posts, comments, and other data. A client that wants to display a user’s profile and recent posts might have to make multiple HTTP requests to different endpoints to get all of the data it needs. This can be inefficient and may require a significant amount of network bandwidth.</p><p>With GraphQL, the client can request all of the data it needs in a single GraphQL query, like this:</p><pre>{<br>  user(id: 123) {<br>    name<br>    email<br>    posts {<br>      title<br>      body<br>      comments {<br>        author<br>        text<br>      }<br>    }<br>  }<br>}</pre><p>The server can then respond with only the requested data, reducing the amount of data transferred and improving the efficiency of the API.</p><p>Here is an example of how the server might implement this GraphQL query:</p><pre>const typeDefs = `<br>  type Query {<br>    user(id: ID!): User<br>  }<br><br>  type User {<br>    name: String<br>    email: String<br>    posts: [Post]<br>  }<br><br>  type Post {<br>    title: String<br>    body: String<br>    comments: [Comment]<br>  }<br><br>  type Comment {<br>    author: String<br>    text: String<br>  }<br>`;<br><br>const resolvers = {<br>  Query: {<br>    user: (root, args) =&gt; {<br>      // Query the database for a user with the specified ID<br>      const user = findUserById(args.id);<br><br>      // Query the database for the user&#39;s posts<br>      const posts = findPostsByUserId(args.id);<br><br>      // Query the database for the comments on each post<br>      posts.forEach(post =&gt; {<br>        post.comments = findCommentsByPostId(post.id);<br>      });<br><br>      return {<br>        name: user.name,<br>        email: user.email,<br>        posts: posts<br>      };<br>    }<br>  }<br>};</pre><p><a href="https://github.com/ad-dhawan/learning_graphql">GitHub - ad-dhawan/learning_graphql: Graph QL is a language and powerful server-side runtime environment for application programming interfaces (APIs) by which you can only get the data that you require and filter out the unwanted data on the backend itself.)</a></p><p>This repository contains resources and code examples for learning GraphQL. It may be a helpful resource if you are interested in learning more about GraphQL and how to use it to build APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c582559a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desktop applications using Electron with React JS]]></title>
            <link>https://medium.com/@ankit.ad.dhawan/desktop-applications-using-electron-with-react-js-80ac96680f39?source=rss-209d72b16940------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ac96680f39</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[desktop-app]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ankit Dhawan]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 21:55:54 GMT</pubDate>
            <atom:updated>2022-08-09T21:55:54.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*Ik7FDhwyhyH9hT4WuVehkw.png" /></figure><p>We have been using desktop applications for over 4 decades and the developers in the respective field are continuously coming up with easier methods to create them. <br><br>In this article, we will see how you can create a desktop application using Electron JS using React framework. Yes, if you can develop websites then you can develop your own desktop application too.</p><h4><strong>What is Electron JS?</strong></h4><p>It is a framework developed by GitHub for creating cross platform desktop applications. It uses Chromium Engine to render and NodeJS as runtime environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejJx36b6dCMAO6N6r83vbA.png" /><figcaption>Apps created using Electron JS</figcaption></figure><p>Let’s start by creating our react application</p><blockquote>npx create-react-app react-electron-app</blockquote><p>The npx command will create a react application in your directory. Once the app is created, navigate to your application directory and install electron in development environment using command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*2dD0gMkGUKi3MtxvcU-7Ug.png" /><figcaption>Basic react application</figcaption></figure><blockquote>npm i -D electron electron-is-dev</blockquote><p>electron-is-dev is a third party package to check if electron app is in development or production environment</p><p>You can check the <em>package.json</em> file if the following packages are installed or not.</p><blockquote>“devDependencies”: {</blockquote><blockquote>“electron”: “²⁰.0.1”,</blockquote><blockquote>“electron-is-dev”: “².0.0”</blockquote><blockquote>}</blockquote><p>The next step is to configure Electron in your project by creating a file in public folder named <em>electron.js</em> and paste the following code in that file</p><blockquote>const path = require(‘path’);</blockquote><blockquote>const { app, BrowserWindow, Menu } = require(‘electron’);</blockquote><blockquote>const isDev = require(‘electron-is-dev’);</blockquote><blockquote>//creating a custom menu</blockquote><blockquote>const menuItems = [</blockquote><blockquote>{</blockquote><blockquote>label: app.name,</blockquote><blockquote>submenu: [</blockquote><blockquote>{ role: ‘about’ },</blockquote><blockquote>{ type: ‘separator’ },</blockquote><blockquote>{ role: ‘services’ },</blockquote><blockquote>{ type: ‘separator’ },</blockquote><blockquote>{ role: ‘hide’ },</blockquote><blockquote>{ role: ‘hideOthers’ },</blockquote><blockquote>{ role: ‘unhide’ },</blockquote><blockquote>{ type: ‘separator’ },</blockquote><blockquote>{ role: ‘quit’ }</blockquote><blockquote>]</blockquote><blockquote>},</blockquote><blockquote>{</blockquote><blockquote>label: ‘Window’,</blockquote><blockquote>submenu: [</blockquote><blockquote>{ role: ‘minimize’ },</blockquote><blockquote>{ role: ‘zoom’ },</blockquote><blockquote>{ type: ‘separator’ },</blockquote><blockquote>{ role: ‘close’ }</blockquote><blockquote>]</blockquote><blockquote>},</blockquote><blockquote>];</blockquote><blockquote>const menu = Menu.buildFromTemplate(menuItems);</blockquote><blockquote>Menu.setApplicationMenu(menu);</blockquote><blockquote>function createWindow() {</blockquote><blockquote>// Create the browser window.</blockquote><blockquote>const win = new BrowserWindow({</blockquote><blockquote>width: 1100,</blockquote><blockquote>height: 600,</blockquote><blockquote>webPreferences: {</blockquote><blockquote>nodeIntegration: true,</blockquote><blockquote>},</blockquote><blockquote>});</blockquote><blockquote>// and load the index.html of the app.</blockquote><blockquote>// win.loadFile(“index.html”);</blockquote><blockquote>win.loadURL(</blockquote><blockquote>isDev</blockquote><blockquote>? ‘http://localhost:3000&#39;</blockquote><blockquote>: `file://${path.join(__dirname, ‘../build/index.html’)}`</blockquote><blockquote>);</blockquote><blockquote>// Open the DevTools.</blockquote><blockquote>if (isDev) {</blockquote><blockquote>//open a developer tool in different window</blockquote><blockquote>win.webContents.openDevTools({ mode: ‘detach’ });</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>// this method will run when electron process is done and the window will be created</blockquote><blockquote>app.whenReady().then(createWindow);</blockquote><blockquote>// quit when all windows are close except MacOS because of default OS behaviour</blockquote><blockquote>app.on(‘window-all-closed’, () =&gt; {</blockquote><blockquote>if (process.platform !== ‘darwin’) {</blockquote><blockquote>app.quit();</blockquote><blockquote>}</blockquote><blockquote>});</blockquote><blockquote>// run the app and open window when clicked on it without quiting the app</blockquote><blockquote>app.on(‘activate’, () =&gt; {</blockquote><blockquote>if (BrowserWindow.getAllWindows().length === 0) {</blockquote><blockquote>createWindow();</blockquote><blockquote>}</blockquote><blockquote>});</blockquote><p>The <em>BrowserWindow</em> class exposes various ways to modify the look and behavior of your app&#39;s windows.</p><p>You can customize your menu by adding or removing labels and submenu as per your requirements.</p><p>After Configuring electron, you need to configure your <em>package.json</em> file</p><p>In package.json file, add this line anywhere before the scripts</p><blockquote>“main”: “public/electron.js”,</blockquote><p>Add two more scripts in <em>package.json </em>file which will run the electron app.</p><blockquote>“scripts”: {</blockquote><blockquote>“start”: “react-scripts start”,</blockquote><blockquote>“build”: “react-scripts build”,</blockquote><blockquote>“test”: “react-scripts test”,</blockquote><blockquote>“eject”: “react-scripts eject”,</blockquote><blockquote>“dev”: “concurrently -k \”BROWSER=none npm start\” \”npm:electron\””,</blockquote><blockquote>“electron”: “wait-on tcp:3000 &amp;&amp; electron .”</blockquote><blockquote>}</blockquote><p>Install these 2 packages in development environment, concurrently &amp; wait-on. These packages will launch the electron app once it listens to the server on the web.You can install the packages using this command</p><blockquote>npm i -D concurrently wait-on</blockquote><h4>DEMO</h4><p>Now that you have setup your electron react app, it’s time to run it</p><p>you can run the react application using this command</p><blockquote>npm run start</blockquote><p>whereas you can run the electron desktop app by using this command</p><blockquote>npm run electron</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0OiXIC1QQwSn_KnypyExQ.png" /><figcaption>Our first electron desktop app using react</figcaption></figure><p>Voila!! You just created your first Desktop application.</p><h4>Conclusion</h4><p>In this article, we covered and learnt how to create a cross platform desktop application using React JS.</p><p>You can find the complete code <a href="https://github.com/ad-dhawan/react-electron-app">here</a></p><p>Follow me on <a href="https://github.com/ad-dhawan">GitHub</a> , <a href="https://www.linkedin.com/in/ankit-dhawan-17b552161/">LinkedIn</a></p><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ac96680f39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>