<?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 Krishan Madushanka on Medium]]></title>
        <description><![CDATA[Stories by Krishan Madushanka on Medium]]></description>
        <link>https://medium.com/@krishanmadushankadev?source=rss-a2cbb9fb735e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-y059kVZXqJ9OGjqYGAOhw.jpeg</url>
            <title>Stories by Krishan Madushanka on Medium</title>
            <link>https://medium.com/@krishanmadushankadev?source=rss-a2cbb9fb735e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:02:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishanmadushankadev/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[Suspense and Lazy Loading in React and React Native: Making Apps Faster]]></title>
            <link>https://krishanmadushankadev.medium.com/suspense-and-lazy-loading-in-react-and-react-native-making-apps-faster-e7cdfc3beb3b?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7cdfc3beb3b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[suspense]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 09:07:40 GMT</pubDate>
            <atom:updated>2026-01-14T09:07:40.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bv--6ouj5Kb9uPM7qzIsqw.png" /></figure><p>Performance is one of the first things users notice in a mobile and web apps and one of the hardest things for developers to get right. As these apps grow, screens become heavier, bundles get larger, and startup time slowly creeps up.</p><p>In this article, we’ll explore what Suspense and lazy loading mean in React Native, how they work, where they shine, and where you need to be careful.</p><h4>The Problem: Loading Everything Upfront</h4><p>By default, many React Native apps load <strong>all screens, components, and logic at startup</strong>. This leads to:</p><ul><li>Slower app launch times</li><li>Increased memory usage</li><li>Unnecessary work for screens users may never visit</li></ul><p>For small apps, this isn’t a big deal. For medium to large apps, it becomes a real performance bottleneck.</p><h4>What Is Lazy Loading?</h4><p><strong>Lazy loading</strong> means loading a component <strong>only when it’s needed</strong>, instead of loading it upfront.</p><p>In React, this is done using React.lazy().</p><h4>Example: Lazy Loading a Screen</h4><pre>import React, { Suspense } from &quot;react&quot;;<br><br>const ProfileScreen = React.lazy(() =&gt; import(&quot;./ProfileScreen&quot;));<br><br>export default function App() {<br>  return (<br>    &lt;Suspense fallback={null}&gt;<br>      &lt;ProfileScreen /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><p>Here’s what happens:</p><ul><li>ProfileScreen is <strong>not loaded immediately</strong></li><li>It loads <strong>only when it’s rendered</strong></li><li>While it loads, React shows the fallback</li></ul><h4>Enter Suspense</h4><p><strong>Suspense</strong> is the mechanism that tells React <em>what to show while something is loading</em>.</p><p>Think of Suspense as a <strong>loading boundary</strong>.</p><pre>&lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>  &lt;HeavyComponent /&gt;<br>&lt;/Suspense&gt;</pre><ul><li>fallback is shown while the component or data is loading</li><li>Once ready, React replaces it with the real UI</li></ul><h4>Lazy Loading Screens in Navigation</h4><p>One of the most practical uses of lazy loading in React Native is with navigation.</p><p><strong>React Navigation Example</strong></p><pre>import React, { Suspense } from &quot;react&quot;;<br>import { View, ActivityIndicator } from &quot;react-native&quot;;<br>import { NavigationContainer } from &quot;@react-navigation/native&quot;;<br>import { createNativeStackNavigator } from &quot;@react-navigation/native-stack&quot;;<br><br>import HomeScreen from &quot;./screens/HomeScreen&quot;;<br><br>const DetailsScreen = React.lazy(() =&gt; import(&quot;./screens/DetailsScreen&quot;));<br><br>const Stack = createNativeStackNavigator();<br><br>function Loader() {<br>  return (<br>    &lt;View style={{ flex: 1, justifyContent: &quot;center&quot;, alignItems: &quot;center&quot; }}&gt;<br>      &lt;ActivityIndicator size=&quot;large&quot; /&gt;<br>    &lt;/View&gt;<br>  );<br>}<br><br>export default function App() {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      &lt;Stack.Navigator&gt;<br>        &lt;Stack.Screen name=&quot;Home&quot; component={HomeScreen} /&gt;<br><br>        &lt;Stack.Screen<br>          name=&quot;Details&quot;<br>          component={() =&gt; (<br>            &lt;Suspense fallback={&lt;Loader /&gt;}&gt;<br>              &lt;DetailsScreen /&gt;<br>            &lt;/Suspense&gt;<br>          )}<br>        /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>  );<br>}</pre><p>It is not a long article just wanted to mention that there is something like this that we can use for code splitting.</p><p>Keep calm and code on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7cdfc3beb3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Split: When to use Fabric vs. TurboModules in React Native]]></title>
            <link>https://krishanmadushankadev.medium.com/the-split-when-to-use-fabric-vs-turbomodules-in-react-native-60f4e56fc3bb?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f4e56fc3bb</guid>
            <category><![CDATA[fscalendar]]></category>
            <category><![CDATA[fabric]]></category>
            <category><![CDATA[turbo-module]]></category>
            <category><![CDATA[native-modules]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 19:20:06 GMT</pubDate>
            <atom:updated>2025-12-30T18:14:52.228Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons learned implementing a custom FSCalendar wrapper.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFFyLd7VIjIbPdplM_N-QQ.jpeg" /></figure><p>I wanted to integrate <a href="https://github.com/WenchaoD/FSCalendar">FSCalendar</a>, a native library written in Swift and Objective-C, into my React Native application. Despite having considerable knowledge about React Native architecture, I encountered numerous challenges during this process. This led me to extensively research articles and consult AI chatbots while going through many trials and errors. In this article, I want to share what I learned throughout this journey.</p><p>My starting point was following an <a href="https://reactnative.dev/docs/turbo-native-modules-introduction?platforms=ios">article from the official React Native documentation</a> about implementing a Turbo Module. I strongly recommend reading that article before continuing here, as I will be referring to several concepts and sections discussed in that documentation.</p><p>The project I used for this integration is a bare React Native project (v0.82.1 — new architecture is enabled by default) that leverages the New Architecture. While I recognize that Expo is currently the prevailing trend, we will focus on writing native modules in a bare project for this article. I believe it is crucial to first understand these concepts at a foundational level, as Expo introduces an additional abstraction layer on top of React Native.</p><p>Since this is a wrapper to a existing UI component in Native side, we don’t need to implement turbo modules. we can implement this warpper for the FSCalendar using the Fabric.</p><h4>1. Codegen configuration</h4><p>Update package.json as follows.</p><pre>{<br>    &quot;name&quot;: &quot;AppSpec&quot;,<br>    &quot;type&quot;: &quot;components&quot;,<br>    &quot;jsSrcsDir&quot;: &quot;specs&quot;,<br>    &quot;ios&quot;: {<br>      &quot;componentProvider&quot;: {<br>        &quot;CustomCalendar&quot;: &quot;RCTFSCalendar&quot;<br>      }<br>    }<br>  }</pre><p>In React Native’s New Architecture (Fabric + TurboModules), the codegenConfig in your package.json includes a “<em>type</em>” field that tells the codegen tool how to process your specs during build time. It generates the necessary bindings based on whether you’re building a <strong>UI-focused component</strong> or a <strong>non-UI native API</strong>. Here’s a breakdown of when to choose each:</p><p><strong>I. type: components (For Fabric Native Views/Components)</strong></p><ul><li>You’re creating or wrapping a <strong>native UI element</strong> (e.g. a custom view, button, or calendar like your FSCalendar integration).</li><li>Focus is on <strong>declarative rendering</strong>: Props for styling/layout (e.g. selectionColor), events (e.g. onDateSelected), and imperative commands (e.g. selectDate via refs).</li><li>Integrates with <strong>ViewManagers</strong> for shadow tree rendering, layout, and batched updates.</li><li>JS Side: Define a native component extending ViewProps interface.</li><li>Make sure to rename the spec file ending with ‘NativeComponent’</li></ul><p><strong>II. type: modules (For TurboModules)</strong></p><ul><li>You’re exposing <strong>non-UI native functionality</strong> (e.g., file I/O, network utils, or calendar date computations without rendering a view).</li><li>Focus is on <strong>imperative, async APIs</strong>: Methods that return promises/callbacks (e.g. fetchEvents(month: string): Promise&lt;string[]&gt;).</li><li>Stands alone; no direct tie to rendering — great for shared logic across screens.</li><li>Generates: JSI executors (e.g., MyModuleSpecJSI.cpp) for direct JS-native calls.</li><li>JS Side: Define a TurboModule spec interface (e.g. export interface Spec extends TurboModule { … }), then TurboModuleRegistry.getEnforcing&lt;Spec&gt;(&#39;MyModule&#39;).</li></ul><p>You can (and often should) have both <strong>Fabric components</strong> (UI views, like your FSCalendar) and <strong>TurboModules</strong> (non-UI native APIs, like a date utils module) in the <em>same project</em> — whether it’s an app or a library. Codegen handles both seamlessly during build, generating separate artifacts.</p><p>The key is proper <strong>spec separation</strong> and codegenConfig setup. Codegen scans your JS/TS files for type-specific markers (e.g., codegenNativeComponent for components vs. TurboModule interfaces for modules) and processes them accordingly. No conflicts — it’s all under one roof.</p><p><strong>Single codegenConfig for Both</strong></p><ul><li>Use a <strong>single config</strong> in your root package.json with a neutral “type” (or omit it for auto-detection). Set jsSrcsDir to scan everything.</li><li>Codegen will auto-classify: Files with component specs get “components” treatment; module specs get “modules.”</li></ul><p><strong>Example package.json for both (not in my code)</strong>:</p><pre>{<br>  &quot;name&quot;: &quot;MyRNProject&quot;,<br>  &quot;codegenConfig&quot;: {<br>    &quot;name&quot;: &quot;MyProject&quot;,  // Namespace for all generated files<br>    &quot;type&quot;: &quot;all&quot;,        // Or omit for auto (RN 0.82+ defaults to scanning both)<br>    &quot;jsSrcsDir&quot;: &quot;./src&quot;  // Scans ./src for all specs; adjust to your folder<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;react-native&quot;: &quot;0.82.1&quot;<br>  }<br>}</pre><h4>2. pod configuration</h4><p>Add pod ‘FSCalendar’ to your pod file and pod install.</p><h4>3. Adding JS code</h4><p>Create file called specs/CalendarNativeComponent.ts</p><p>The specification file must be named &lt;MODULE_NAME&gt;NativeComponent.{ts|js} to work with Codegen. The suffix NativeComponent is not only a convention, it is actually used by Codegen to detect a spec file.</p><pre>import type { HostComponent, ViewProps } from &#39;react-native&#39;;<br>import { codegenNativeComponent, ProcessedColorValue } from &#39;react-native&#39;;<br>import {<br>  DirectEventHandler,<br>  Int32,<br>} from &#39;react-native/Libraries/Types/CodegenTypes&#39;;<br>import codegenNativeCommands from &#39;react-native/Libraries/Utilities/codegenNativeCommands&#39;;<br><br>type DateSelectedEvent = {<br>  date: string;<br>};<br><br>type MonthChangedEvent = {<br>  month: string;<br>};<br><br>export interface NativeProps extends ViewProps {<br>  // Events<br>  onDateSelected?: DirectEventHandler&lt;DateSelectedEvent&gt;;<br>  onMonthChanged?: DirectEventHandler&lt;MonthChangedEvent&gt;;<br><br>  // Props<br>  firstWeekday?: Int32;<br>  selectionColor?: ProcessedColorValue | null;<br>  todayColor?: ProcessedColorValue | null;<br>  headerTitleColor?: ProcessedColorValue | null;<br>  weekdayTextColor?: ProcessedColorValue | null;<br>  eventDates?: string[];<br>}<br><br>export interface CalendarRef {<br>  setCurrentPage: (date: string) =&gt; void;<br>  addEvent: (date: string) =&gt; void;<br>}<br><br>export interface NativeCommands {<br>  setCurrentPage: (viewRef: React.ElementRef&lt;HostComponent&lt;NativeProps&gt;&gt;, date: string) =&gt; void;<br>  addEvent: (viewRef: React.ElementRef&lt;HostComponent&lt;NativeProps&gt;&gt;, date: string) =&gt; void;<br>}<br><br>export const Commands: NativeCommands = codegenNativeCommands&lt;NativeCommands&gt;({<br>  supportedCommands: [&#39;setCurrentPage&#39;, &#39;addEvent&#39;],<br>});<br><br>export default codegenNativeComponent&lt;NativeProps&gt;(<br>  &#39;CustomCalendar&#39;,<br>) as HostComponent&lt;NativeProps&gt;;</pre><p>Now run</p><p>cd ios<br>bundle install<br>bundle exec pod install</p><p>This will generate the necessary glue code using codegen.</p><p>Create a file called src/Calendar.tsx</p><pre>import React, { forwardRef, useRef, useImperativeHandle } from &#39;react&#39;;<br>import { ViewStyle, processColor } from &#39;react-native&#39;;<br>import CalendarNativeComponent from &#39;../specs/CalendarNativeComponent&#39;;<br>import { Commands, CalendarRef } from &#39;../specs/CalendarNativeComponent&#39;;<br><br>export interface CalendarProps {<br>  style?: ViewStyle;<br>  firstWeekday?: number;<br>  selectionColor?: string;<br>  todayColor?: string;<br>  headerTitleColor?: string;<br>  weekdayTextColor?: string;<br>  eventDates?: string[];<br>  onDateSelected?: (date: string) =&gt; void;<br>  onMonthChanged?: (month: string) =&gt; void;<br>}<br><br>const Calendar = forwardRef&lt;CalendarRef, CalendarProps&gt;(({<br>  style,<br>  firstWeekday = 1,<br>  selectionColor = &#39;#000000ff&#39;,<br>  todayColor = &#39;rgba(107, 235, 255, 1)&#39;,<br>  headerTitleColor = &#39;rgba(107, 77, 255, 1)&#39;,<br>  weekdayTextColor = &#39;rgba(0, 0, 0, 1)&#39;,<br>  eventDates = [],<br>  onDateSelected,<br>  onMonthChanged,<br>}, ref) =&gt; {<br>  const nativeRef = useRef(null);<br><br>  useImperativeHandle(ref, () =&gt; ({<br>    setCurrentPage: (date: string) =&gt; {<br>      if (nativeRef.current) {<br>        Commands.setCurrentPage(nativeRef.current, date);<br>      }<br>    },<br>    addEvent: (date: string) =&gt; {<br>      if (nativeRef.current) {<br>        Commands.addEvent(nativeRef.current, date);<br>      }<br>    },<br>  }));<br><br>  return (<br>    &lt;CalendarNativeComponent<br>      ref={nativeRef}<br>      style={style}<br>      firstWeekday={firstWeekday}<br>      selectionColor={processColor(selectionColor)}<br>      todayColor={processColor(todayColor)}<br>      headerTitleColor={processColor(headerTitleColor)}<br>      weekdayTextColor={processColor(weekdayTextColor)}<br>      eventDates={eventDates}<br>      onDateSelected={(event) =&gt; {<br>        onDateSelected?.(event.nativeEvent.date);<br>      }}<br>      onMonthChanged={(event) =&gt; {<br>        onMonthChanged?.(event.nativeEvent.month);<br>      }}<br>    /&gt;<br>  );<br>});<br><br>Calendar.displayName = &#39;Calendar&#39;;<br><br>export default Calendar;</pre><p>Imperative Commands (Fabric Commands) are defined in above code. The code has a ref to the native element and executes commands(add events, slect date etc.)on it.</p><ul><li><strong>Note that we pass a ref to native side that we can directly call commands on the UI element.</strong></li></ul><p>Add code to App.tsx</p><pre>import React, { useRef, useState } from &#39;react&#39;;<br>import {<br>  SafeAreaView,<br>  StyleSheet,<br>  Text,<br>  View,<br>  Button,<br>  ScrollView,<br>} from &#39;react-native&#39;;<br>import Calendar from &#39;./src/Calendar&#39;;<br>import { CalendarRef } from &#39;./specs/CalendarNativeComponent&#39;;<br><br>function App(): React.JSX.Element {<br>  const [selectedDate, setSelectedDate] = useState&lt;string&gt;(&#39;&#39;);<br>  const [currentMonth, setCurrentMonth] = useState&lt;string&gt;(&#39;&#39;);<br>   const calendarRef = useRef&lt;CalendarRef&gt;(null);<br><br>  const handleDateSelected = (date: string) =&gt; {<br>    console.log(&#39;Date selected:&#39;, date);<br>    setSelectedDate(date);<br>  };<br><br>  const handleMonthChanged = (month: string) =&gt; {<br>    console.log(&#39;Month changed:&#39;, month);<br>    setCurrentMonth(month);<br>  };<br><br>  const addEventToday = () =&gt; {<br>    const today = new Date().toISOString().split(&#39;T&#39;)[0];<br>    calendarRef.current?.addEvent(today);<br>  };<br><br>  const goToToday = () =&gt; {<br>    const today = new Date().toISOString().split(&#39;T&#39;)[0];<br>    calendarRef.current?.setCurrentPage(today);<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>      &lt;ScrollView&gt;<br>        &lt;View style={styles.header}&gt;<br>          &lt;Text style={styles.title}&gt;FSCalendar Example&lt;/Text&gt;<br>          {selectedDate ? (<br>            &lt;Text style={styles.selectedText}&gt;<br>              Selected Date: {selectedDate}<br>            &lt;/Text&gt;<br>          ) : null}<br>          {currentMonth ? (<br>            &lt;Text style={styles.selectedText}&gt;<br>              Selected Month: {currentMonth}<br>            &lt;/Text&gt;<br>          ) : null}<br>        &lt;/View&gt;<br><br>        &lt;Calendar<br>          ref={calendarRef}<br>          style={styles.calendar}<br>          onDateSelected={handleDateSelected}<br>          onMonthChanged={handleMonthChanged}<br>          firstWeekday={1} // Monday<br>          // scope=&quot;month&quot;<br>          selectionColor=&quot;#3366FF&quot;<br>          todayColor=&quot;#FF9500&quot;<br>          headerTitleColor=&quot;#000000&quot;<br>          weekdayTextColor=&quot;#666666&quot;<br>          eventDates={[&#39;2025-11-28&#39;]}<br>        /&gt;<br><br>        &lt;View style={styles.buttonContainer}&gt;<br>          &lt;Button title=&quot;Add Event Today&quot; onPress={addEventToday} /&gt;<br>          &lt;View style={styles.spacing} /&gt;<br>          &lt;Button title=&quot;Go to Today&quot; onPress={goToToday} /&gt;<br>        &lt;/View&gt;<br>      &lt;/ScrollView&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;#F5F5F5&#39;,<br>  },<br>  header: {<br>    padding: 20,<br>    backgroundColor: &#39;white&#39;,<br>  },<br>  title: {<br>    fontSize: 24,<br>    fontWeight: &#39;bold&#39;,<br>    marginBottom: 10,<br>  },<br>  selectedText: {<br>    fontSize: 16,<br>    color: &#39;#666&#39;,<br>  },<br>  calendar: {<br>    height: 350,<br>    backgroundColor: &#39;white&#39;,<br>    margin: 10,<br>    borderRadius: 10,<br>  },<br>  buttonContainer: {<br>    padding: 20,<br>  },<br>  spacing: {<br>    height: 10,<br>  },<br>});<br><br>export default App;</pre><h4>4.Native codes</h4><p>Create a group in code called, NativeFSCalendar and create following files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*IUf5h14IQ5C-PMaxsB5ENQ.png" /></figure><p>.h files define the structure and the .m files have the implementation for that structure. This is a common pattern in Objective-C world. if you want to add c++ code also in mix with C, then use the .mm file extension.</p><p>I. <strong>RCTFSCalendar.mm</strong> (The Core View Logic Layer)</p><pre>//<br>//  RCTFSCalendar.mm<br>//  Demo<br>//<br>//  Created by Krishan Madushanka on 2025-12-06.<br>//<br><br>#import &quot;RCTFSCalendar.h&quot;<br><br>#import &lt;react/renderer/components/AppSpec/ComponentDescriptors.h&gt;<br>#import &lt;react/renderer/components/AppSpec/EventEmitters.h&gt;<br>#import &lt;react/renderer/components/AppSpec/Props.h&gt;<br>#import &lt;react/renderer/components/AppSpec/RCTComponentViewHelpers.h&gt;<br>#import &lt;FSCalendar/FSCalendar.h&gt;<br><br>using namespace facebook::react;<br><br>@interface RCTFSCalendar () &lt;RCTCustomCalendarViewProtocol, FSCalendarDelegate, FSCalendarDataSource&gt;<br>@end<br><br>@implementation RCTFSCalendar {<br>  FSCalendar *_calendar;<br>  NSMutableArray&lt;NSString *&gt; *_eventDates;<br>}<br><br>- (instancetype)init<br>{<br>  if (self = [super init]) {<br>    _calendar = [[FSCalendar alloc] initWithFrame:CGRectZero];<br>    _calendar.delegate = self;<br>    _calendar.dataSource = self;<br>    _eventDates = [NSMutableArray array];<br>    [self addSubview:_calendar];<br>  }<br>  return self;<br>}<br><br>- (void)updateProps:(Props::Shared const &amp;)props oldProps:(Props::Shared const &amp;)oldProps<br>{<br>  const auto &amp;oldViewProps = *std::static_pointer_cast&lt;CustomCalendarProps const&gt;(_props);<br>  const auto &amp;newViewProps = *std::static_pointer_cast&lt;CustomCalendarProps const&gt;(props);<br>  <br>  // Handle firstWeekday<br>  if (oldViewProps.firstWeekday != newViewProps.firstWeekday) {<br>    _calendar.firstWeekday = newViewProps.firstWeekday;<br>  }<br>  <br>  // Handle selectionColor<br>  if (oldViewProps.selectionColor != newViewProps.selectionColor) {<br>    _calendar.appearance.selectionColor = [self colorFromSharedColor:newViewProps.selectionColor];<br>  }<br>  <br>  // Handle todayColor<br>  if (oldViewProps.todayColor != newViewProps.todayColor) {<br>    _calendar.appearance.todayColor = [self colorFromSharedColor:newViewProps.todayColor];<br>  }<br>  <br>  // Handle headerTitleColor<br>  if (oldViewProps.headerTitleColor != newViewProps.headerTitleColor) {<br>    _calendar.appearance.headerTitleColor = [self colorFromSharedColor:newViewProps.headerTitleColor];<br>  }<br>  <br>  // Handle weekdayTextColor<br>  if (oldViewProps.weekdayTextColor != newViewProps.weekdayTextColor) {<br>      _calendar.appearance.weekdayTextColor = [self colorFromSharedColor:newViewProps.weekdayTextColor];<br>  }<br>  <br>  // Handle eventDates<br>  if (oldViewProps.eventDates != newViewProps.eventDates) {<br>    [_eventDates removeAllObjects];<br>    for (const auto &amp;dateStr : newViewProps.eventDates) {<br>      NSString *nsDateStr = [NSString stringWithCString:dateStr.c_str() encoding:NSUTF8StringEncoding];<br>      [_eventDates addObject:nsDateStr];<br>    }<br>    [_calendar reloadData];<br>  }<br>  <br>  [super updateProps:props oldProps:oldProps];<br>}<br><br>- (void)layoutSubviews<br>{<br>  [super layoutSubviews];<br>  _calendar.frame = self.bounds;<br>}<br><br>#pragma mark - RCTCustomCalendarViewProtocol<br><br>- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args<br>{<br>  RCTCustomCalendarHandleCommand(self, commandName, args);<br>}<br><br>#pragma mark - Commands<br><br>- (void)setCurrentPage:(NSString *)date<br>{<br>  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];<br>  [formatter setDateFormat:@&quot;yyyy-MM-dd&quot;];<br>  NSDate *targetDate = [formatter dateFromString:date];<br>  <br>  if (targetDate) {<br>    [_calendar setCurrentPage:targetDate animated:YES];<br>  }<br>}<br><br>- (void)addEvent:(NSString *)date<br>{<br>  if (![_eventDates containsObject:date]) {<br>    [_eventDates addObject:date];<br>    [_calendar reloadData];<br>  }<br>}<br><br>#pragma mark - FSCalendarDelegate<br><br>- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition<br>{<br>  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];<br>  [formatter setDateFormat:@&quot;yyyy-MM-dd&quot;];<br>  NSString *dateString = [formatter stringFromDate:date];<br>  <br>  CustomCalendarEventEmitter::OnDateSelected event = CustomCalendarEventEmitter::OnDateSelected{<br>    CustomCalendarEventEmitter::OnDateSelected{std::string([dateString UTF8String])}<br>  };<br>  self.eventEmitter.onDateSelected(event);<br>}<br><br>- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar<br>{<br>  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];<br>  [formatter setDateFormat:@&quot;yyyy-MM&quot;];<br>  NSString *monthString = [formatter stringFromDate:calendar.currentPage];<br>  <br>  CustomCalendarEventEmitter::OnMonthChanged event = CustomCalendarEventEmitter::OnMonthChanged{<br>    CustomCalendarEventEmitter::OnMonthChanged{std::string([monthString UTF8String])}<br>  };<br>  self.eventEmitter.onMonthChanged(event);<br>}<br><br>#pragma mark - FSCalendarDataSource<br><br>- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date<br>{<br>  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];<br>  [formatter setDateFormat:@&quot;yyyy-MM-dd&quot;];<br>  NSString *dateString = [formatter stringFromDate:date];<br>  <br>  if (_eventDates &amp;&amp; [_eventDates containsObject:dateString]) {<br>    return 1;<br>  }<br>  return 0;<br>}<br><br>#pragma mark - Helpers<br><br>- (UIColor *)colorFromSharedColor:(const SharedColor &amp;)sharedColor {<br>    if (!sharedColor) {<br>        return nil;<br>    }<br>    <br>    auto colorComponents = colorComponentsFromColor(sharedColor);<br>    <br>    CGFloat alpha = colorComponents.alpha;<br>    if (alpha == 0.0) {<br>        alpha = 1.0;<br>    }<br>    <br>    return [UIColor colorWithRed:colorComponents.red<br>                           green:colorComponents.green<br>                            blue:colorComponents.blue<br>                           alpha:alpha];<br>}<br><br>// Event emitter convenience method<br>- (const CustomCalendarEventEmitter &amp;)eventEmitter<br>{<br>  return static_cast&lt;const CustomCalendarEventEmitter &amp;&gt;(*_eventEmitter);<br>}<br><br>+ (ComponentDescriptorProvider)componentDescriptorProvider<br>{<br>  return concreteComponentDescriptorProvider&lt;CustomCalendarComponentDescriptor&gt;();<br>}<br><br>@end</pre><p>This directly wraps and manages the FSCalendar instance. Responsible for rendering the calendar UI, processing props into native appearance changes, and responding to user interactions via delegates.</p><p><strong>II. RCTFSCalendar.h</strong></p><h4>5. Final Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*7Ae0P5mwlHisq7RGfK7sww.gif" /></figure><blockquote>Clone the full code from<strong> </strong><a href="https://github.com/KrishanMadushanka/FSCalendarNewArch"><strong>here.</strong></a></blockquote><h4>Fabric vs. TurboModules: The Clear Separation</h4><ul><li><strong>Fabric</strong>: The renderer for UI components. It builds a shadow tree for fast layouts, batches prop updates, and dispatches events/commands. Use it for <em>views</em> — anything declarative like &lt;MyCalendar eventDates={[]}/&gt;.</li><li><strong>TurboModules</strong>: Asynchronous native modules for non-UI logic (e.g. file I/O, database or date computations). They use <strong>JSI</strong> for low-latency JS-native calls, lazy-loading on demand. We can call the native apis thrugh the codegen generated <strong><em>glue code</em></strong>.</li></ul><p>In my code, Fabric dominated: Props flowed from JS to native setters (e.g., setSelectionColor parsing hex strings), events bubbled back (e.g., didSelectDate firing onDateSelected), and commands routed via codegen glue code.</p><p><strong>Example Flow: Prop Update (Fabric-Only)</strong></p><ol><li>JS: &lt;FSCalendarView selectionColor=”#3366FF” /&gt;.</li><li>Fabric: Serializes prop via shadow tree.</li><li>Native: ViewManager calls -setSelectionColor, which applies calendar.appearance.selectionColor.</li></ol><p><strong>No TurboModules needed</strong> — it’s pure UI.</p><p>In <a href="https://reactnative.dev/docs/turbo-native-modules-introduction?platforms=ios">react native documentation article</a>, note that it shows how to write an implementation of the <a href="https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage-dev">Web Storage API</a>: <strong>localStorage</strong> , which wants to access to the APIs available in native sides to deal with localStorage. In that case we want to implement a Turbo Module — No UI.</p><ul><li>In a Turbo Module you need to define a spec file in JS side,</li></ul><pre>import type {TurboModule} from &#39;react-native&#39;;<br>import {TurboModuleRegistry} from &#39;react-native&#39;;<br><br>export interface Spec extends TurboModule {<br>  setItem(value: string, key: string): void;<br>  getItem(key: string): string | null;<br>  removeItem(key: string): void;<br>  clear(): void;<br>}<br>export default TurboModuleRegistry.getEnforcing&lt;Spec&gt;(<br>  &#39;NativeLocalStorage&#39;,<br>);</pre><p>and generate <strong>glue code </strong>by running ,</p><pre>cd ios<br>bundle install<br>bundle exec pod install</pre><p>using <strong>codegen </strong>for that file. Then implement the APIs in native side which JS side will call.</p><pre>import NativeLocalStorage from &#39;./specs/NativeLocalStorage&#39;;<br><br>function saveValue() {<br>   //call native method from js side.<br>   NativeLocalStorage?.setItem(editingValue ?? EMPTY, &#39;myKey&#39;);<br>}</pre><p>Also we can use both(module and components) in combination whenever needed.</p><p>You can find the expo module implementation for FSCalendar from <a href="https://github.com/KrishanMadushanka/ExpoModuleApp">this</a> <a href="https://github.com/KrishanMadushanka/ExpoModuleApp">link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f4e56fc3bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Generator Functions in JavaScript — When to Use Them]]></title>
            <link>https://krishanmadushankadev.medium.com/understanding-generator-functions-in-javascript-when-to-use-them-c60937ba481e?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60937ba481e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[generator-functions-in-js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 11:33:42 GMT</pubDate>
            <atom:updated>2025-11-04T11:33:42.655Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Generator Functions in JavaScript — When to Use Them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlLs-sjDO6nj4MDOf_c81A.png" /></figure><p>It’s been a while since I last wrote on Medium, but after a busy schedule, I thought I’d share something new I learned recently.</p><h4>What are Generator Functions?</h4><p>Generator functions are a powerful feature in modern <strong>JavaScript (ES6+)</strong> that offer a way to work with sequences and manage asynchronous operations. Unlike regular functions that run to completion, generators can be <strong>paused and resumed</strong>, giving you precise control over their execution flow. It uses function* syntax. When called, it doesn&#39;t immediately execute its code but instead returns a <strong>Generator object</strong>, which is an <strong>iterator.</strong></p><h4>Key Characteristics</h4><ul><li><strong>Iterable by Nature</strong>: Generators return an iterator object, allowing you to consume values lazily (on demand).</li><li><strong>Pause and Resume</strong>: Unlike regular functions, which run to completion, generators can suspend execution at yield points and resume from there later.</li><li><strong>Bidirectional Communication</strong>: You can pass values <em>into</em> the generator using next(value) after yielding.</li><li><strong>No Blocking</strong>: This makes them ideal for non-blocking operations, like handling async flows without callbacks or promises.</li></ul><h4>Basic Generator: Yielding Values</h4><pre>function* numberGenerator(max) {<br>  let current = 0;<br>  while (current &lt; max) {<br>    yield current;  // Pauses here, yields the value<br>    current++;<br>  }<br>}<br><br>// Usage<br>const gen = numberGenerator(3);<br>console.log(gen.next());  // { value: 0, done: false }<br>console.log(gen.next());  // { value: 1, done: false }<br>console.log(gen.next());  // { value: 2, done: false }<br>console.log(gen.next());  // { value: undefined, done: true }</pre><p>Each next() call resumes the function from the last yield, producing the next value. The returned object has a value (what was yielded) and done (boolean indicating if the generator is exhausted).</p><h4>Passing Values Back to the Generator</h4><p>Generators can receive input via next(value), which becomes the result of the previous yield.</p><pre>function* interactiveGenerator() {<br>  const name = yield &#39;What is your name?&#39;;  // First yield<br>  const age = yield `Hi ${name}, how old are you?`;  // Receives &#39;name&#39; as input<br>  return `User: ${name}, Age: ${age}`;<br>}<br><br>const gen = interactiveGenerator();<br>console.log(gen.next());  // { value: &#39;What is your name?&#39;, done: false }<br>console.log(gen.next(&#39;Alice&#39;));  // { value: &#39;Hi Alice, how old are you?&#39;, done: false }<br>console.log(gen.next(&#39;30&#39;));  // { value: &#39;User: Alice, Age: 30&#39;, done: true }</pre><h4>Use Cases: When Do We Need Generators?</h4><p>Generators aren’t always necessary — promises, async/await, and RxJS observables often suffice.But they excel in scenarios requiring fine-grained control over iteration or suspension.</p><p>This gets to the <em>real</em> power of generators in React or React Native when you’re dealing with <strong>blocking operations</strong> or <strong>long-running loops</strong> that would normally freeze the JS thread.</p><p>If you run a <strong>long synchronous loop</strong> (like processing a large dataset, parsing a huge JSON, or doing math-heavy operations), the JS thread gets blocked — meaning : <strong>The UI can’t update.</strong></p><p>Example of blocking code</p><pre>function heavyComputation() {<br>  let sum = 0;<br>  for (let i = 0; i &lt; 1e9; i++) {<br>    sum += i;<br>  }<br>  return sum;<br>}</pre><pre>useEffect(() =&gt; {<br>  const result = heavyComputation(); // UI freezes until done<br>  console.log(result);<br>}, []);</pre><p>Generators let you <strong>split a long task into chunks</strong> and <strong>yield control back to the event loop</strong> between iterations.<br>That means React (or the browser) gets breathing room to update the UI or respond to input , without freezing.</p><h4>With Generators (non-blocking):</h4><pre>function* computeLargeSum(numbers) {<br>  let total = 0;<br>  for (let i = 0; i &lt; numbers.length; i++) {<br>    total += numbers[i];<br>    if (i % 100000 === 0) yield total; // pause every 100k iterations<br>  }<br>  return total;<br>}<br><br>export default function App() {<br>  const [progress, setProgress] = useState(0);<br>  const [done, setDone] = useState(false);<br><br>  useEffect(() =&gt; {<br>    const numbers = Array.from({ length: 1e7 }, (_, i) =&gt; i);<br>    const iterator = computeLargeSum(numbers);<br><br>    function run() {<br>      const { value, done } = iterator.next();<br>      if (!done) {<br>        setProgress(value);<br>        requestIdleCallback(run); // let the browser breathe<br>      } else {<br>        setProgress(value);<br>        setDone(true);<br>      }<br>    }<br><br>    run();<br>  }, []);<br><br>  return (<br>    &lt;View style={{ padding: 20 }}&gt;<br>      &lt;Text&gt;Progress: {progress}&lt;/Text&gt;<br>      {done &amp;&amp; &lt;Text&gt;Finished!&lt;/Text&gt;}<br>    &lt;/View&gt;<br>  );<br>}</pre><ul><li>The generator <strong>pauses (yeild) every 100k iterations</strong>.</li><li>Each pause lets the browser or JS engine process UI updates or user input.</li><li>requestIdleCallback (or setTimeout) resumes execution without freezing the app.</li></ul><p>Thanks for reading. Your feedback is appreciated. 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60937ba481e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Choose Zustand Over Redux?]]></title>
            <link>https://krishanmadushankadev.medium.com/why-choose-zustand-over-redux-9103d9122d14?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9103d9122d14</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 16:52:31 GMT</pubDate>
            <atom:updated>2025-04-30T16:52:31.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2cV6LiBr0TzHPL0gsIbVWQ.jpeg" /></figure><p>When it comes to managing state in React applications, Redux has long been the go-to solution for developers. Its predictable state container and robust ecosystem made it a staple in many large-scale projects. Over time, it became the default choice for handling complex application states, especially in scenarios involving deeply nested components or extensive data flow across the application.</p><p>While Redux remains a powerful tool, its boilerplate and setup overhead and steep learning curve have led many developers to explore more lightweight and intuitive alternatives. One such solution gaining significant traction in the React ecosystem is <strong>Zustand</strong>.</p><p><strong>Zustand </strong>offers a minimalistic yet flexible approach to state management. It eliminates the need for reducers, action types, and context providers, allowing developers to create global state with just a few lines of code. Zustand’s API is built around simplicity and performance, leveraging native JavaScript patterns to manage state efficiently. It also works seamlessly with TypeScript, offering strong typing without additional configuration.</p><h3>Key Advantages of Zustand Over Redux</h3><h4>Dramatically Less Boilerplate</h4><ul><li><strong>Redux</strong>: Requires actions, reducers, dispatchers, selectors, and often Redux Toolkit to reduce complexity. The learning curve is also steep due to this.</li><li><strong>Zustand</strong>: Just define state and actions in one simple create function.</li></ul><pre>// Zustand Store<br>const useStore = create(set =&gt; ({<br>  count: 0,<br>  increment: () =&gt; set(state =&gt; ({ count: state.count + 1 }))<br>})<br><br>// Component<br>const count = useStore(state =&gt; state.count)<br>const increment = useStore(state =&gt; state.increment)</pre><h4>No Provider Wrapper Needed</h4><ul><li><strong>Redux</strong>: Requires &lt;Provider store={store}&gt; at app root</li><li><strong>Zustand</strong>: Works without any context provider</li></ul><h4>Built-in Support for Async Actions</h4><ul><li><strong>Redux</strong>: Need to use Thunk or Redux toolkit support</li><li><strong>Zustand</strong>: No middleware needed for async operations</li></ul><pre>fetchUsers: async () =&gt; {<br>  const users = await api.getUsers()<br>  set({ users })<br>}</pre><h4>Developer Experience</h4><ul><li><strong>Learning Curve</strong>: Zustand is much easier to learn</li><li><strong>TypeScript</strong>: Zustand has excellent TS support out of the box</li><li><strong>Community</strong>: Redux has more documentation/tutorials, but Zustand’s API is simple enough to need less</li></ul><h3>The Verdict</h3><p><strong>Choose Zustand if you:</strong></p><ul><li>Want simple, clean state management</li><li>Are starting a new project</li><li>Prefer writing less code</li><li>Don’t need advanced Redux DevTools features</li></ul><p><strong>Stick with Redux if you:</strong></p><ul><li>Have an existing large Redux codebase</li><li>Need advanced middleware capabilities</li><li>Work on a team that already knows Redux well</li></ul><p>For most React and React Native applications in 2023+, Zustand provides a better developer experience with nearly all the capabilities of Redux and none of the boilerplate. It’s particularly well-suited for:</p><ul><li>Small to medium-sized apps</li><li>Rapid prototyping</li><li>Projects where simplicity is valued</li></ul><p>The choice ultimately depends on your specific needs, but Zustand has become the preferred solution for many modern React applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9103d9122d14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing custom expo plugin to integrate a third party library.]]></title>
            <link>https://krishanmadushankadev.medium.com/writing-custom-expo-plugin-to-integrate-a-third-party-library-6d43f4efdab3?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d43f4efdab3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[smile-identity]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 07:51:17 GMT</pubDate>
            <atom:updated>2025-02-04T07:56:42.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HRh3f9E7T0Gqzc8rlSCG_w.png" /></figure><p>I was working on a react native Expo project in last months and I had the opportunity to learn how to write a expo plugin while the existing plugins don’t help me with my task. I had to run through lot of trial and error scenarios since the resources for this topic is limited. Therefore, I thought of sharing my experience in writing a simple Expo plugin while also sharing the knowledge I gained after burning a few midnights.</p><h4>When Do You Need an Expo Config Plugin ?</h4><p>An <strong>Expo config plugin</strong> is needed when you have to modify the native code or configuration of an Expo project that <strong>managed workflow</strong> does not support out of the box. Since Expo projects do not include native iOS or Android code by default, a config plugin allows you to make <strong>custom native changes.</strong></p><p>Simply, if you want to work on Expo bare react native project you have to run command,</p><pre>npx expo prebuild</pre><p>inside your project directory which results generating ios and android directories. If you want to do any changes inside those native folders you have to use a config plugin. There are existing plugins that we can use in this case.</p><p>For example, if you want to chnge any build properties in android and ios side you can use <a href="https://docs.expo.dev/versions/latest/sdk/build-properties/">expo-build-properties</a> plugin for that. For that you have to install it as mentioned in the documentation and add in app.json or app.config.js file.</p><pre>{<br>  &quot;expo&quot;: {<br>    &quot;plugins&quot;: [<br>      [<br>        &quot;expo-build-properties&quot;,<br>        {<br>          &quot;android&quot;: {<br>            &quot;compileSdkVersion&quot;: 34,<br>            &quot;targetSdkVersion&quot;: 34,<br>            &quot;buildToolsVersion&quot;: &quot;34.0.0&quot;<br>          },<br>          &quot;ios&quot;: {<br>            &quot;deploymentTarget&quot;: &quot;13.4&quot;<br>          }<br>        }<br>      ]<br>    ]<br>  }<br>}</pre><p>After adding above values in app.json and running <strong>npx expo prebuild </strong>command, the properties will be added automatically (bythe plugin) in native side. Always remember that there is no point that we manually do changes in native side since <strong>prebuild </strong>command will destroy every change that we did manually since it generates android and ios directories newly.</p><h4>When Do You Need an Custom Plugin ?</h4><p>Think of a situation where there is no prebuilt plugins that does the task you want to do. For example think of a third party library that needs native side configurations that doesn’t support expo and only supports bare react native. In that case you have to write your own plugin to do the necessary changes in native side.</p><p>In my case it was the integrating of a library called <a href="https://docs.usesmileid.com/">smile id</a> used for KYC integration. From now on we’ll see how we can integrate this library with a custom expo plugin.</p><h4>Configuring smile id library in expo project</h4><p>First install the library in to your project using the npm command,</p><pre>npm i @smile_identity/react-native</pre><p>Now what we have to do here in native side is (given in the documentation),</p><p><strong>Android</strong></p><blockquote>Place the smile_config.json file under your application&#39;s assets, located at src/main/assets (This should be at the same level as your java and res directories)</blockquote><p><strong>iOS</strong></p><blockquote>Drag the smile_config.json file into your projects file inspector and ensure that the file is added to your app&#39;s target. Confirm that it is by checking the Copy Bundle Resources drop down in the Build Phases tab of Xcode.</blockquote><p>I copied above from the documentation and it says how to integrate this with a bare react native project but, since our project is expo, we have to do above changes in native side with a custom plugin. All the configurations related to smile id is inside this smile_config.json<em> </em>file and we have to add that file to native side as mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*PRlICkdnuzWLVt6EhjhBKA.png" /></figure><p>I have created a directory in root of the expo project called plugins and added a file called copy-file-config.js. Inside config directory I have placed the file that we want to move to native side.</p><h4>Writing the plugin</h4><p>First we have open the app.json file and add our plugin inside plugins array.</p><pre>{<br>  &quot;expo&quot;: {<br>    // other configurations<br>    &quot;plugins&quot;: [<br>      // other plugins<br>      [<br>        &quot;./plugins/copy-file-config&quot;,<br>        {<br>          &quot;src&quot;: &quot;./config/smile_config.json&quot;,<br>          &quot;iosDest&quot;: &quot;smile_config.json&quot;,<br>          &quot;androidDest&quot;: &quot;app/src/main/assets/smile_config.json&quot;,<br>          &quot;groupName&quot;: &quot;&lt;ios group name here&gt;&quot;<br>        }<br>      ],<br>    ],<br>    // other configurations<br>  }<br>}</pre><p><strong>src</strong> — path to config file in js side<br><strong>iosDest</strong> — ios destination that we have to copy the file<br><strong>androidDest</strong> — android destination that we have to copy the file<br><strong>groupName</strong> — Xcode group name where we should add the file <br>We’ll use above variables while writing the plugin.</p><p>Now lets start writing plugin with android part first. Add the following code in copy-file-config.js.</p><pre>const fs = require(&quot;fs&quot;);<br>const path = require(&quot;path&quot;);<br>const {<br>  withPlugins,<br>  withAndroidManifest,<br>} = require(&quot;@expo/config-plugins&quot;);<br><br>const withMyConfigFile = (config, { src, iosDest, androidDest, groupName }) =&gt; {<br>  return withPlugins(config, [<br>    (config) =&gt; withAndroidConfigFile(config, { src, dest: androidDest }),<br>  ]);<br>};<br><br>const withAndroidConfigFile = (config, { src, dest }) =&gt; {<br>  return withAndroidManifest(config, async (config) =&gt; {<br>    const sourcePath = path.resolve(__dirname, src); <br>    const destinationPath = path.resolve(<br>      config.modRequest.platformProjectRoot,<br>      dest<br>    );<br><br>    try {<br>      // Copy the file to the destination directory<br>      if (!fs.existsSync(sourcePath)) {<br>        throw new Error(`Source file not found at ${sourcePath}`);<br>      }<br><br>      const destDir = path.dirname(destinationPath);<br>      if (!fs.existsSync(destDir)) {<br>        fs.mkdirSync(destDir, { recursive: true });<br>      }<br><br>      fs.copyFileSync(sourcePath, destinationPath);<br>    } catch (error) {<br>      console.error(`Error copying ${src} to Android:`, error.message);<br>      throw error;<br>    }<br><br>    return config;<br>  });<br>};<br><br>module.exports = withMyConfigFile;</pre><p>With android it is pretty straightforward since we have to copy the file from source to destination. You have to import withPlugins and withAndroidManifest modules from @expo/config-plugins and we write the file copying inside withAndroidConfigFile<em> </em>which is passed to withPlugins<em> </em>inside<em> </em>withMyConfigFile<em>.</em></p><pre>const withMyConfigFile = (config, { src, iosDest, androidDest, groupName }) =&gt; {<br>  return withPlugins(config, [<br>    (config) =&gt; withAndroidConfigFile(config, { src, dest: androidDest }),<br>  ]);<br>};</pre><ul><li>Registers a <strong>custom Expo Config Plugin</strong> that <strong>adds a config file (</strong>smile_config.json<strong>) </strong>to the <strong>Android project</strong>.</li><li>It wraps config using withPlugins, ensuring that withAndroidConfigFile gets executed.</li><li>We have passed src and dest to withAndroidConfigFile<em> </em>so that function can copy the file from given source path to destination.</li></ul><p>I won’t discuss the code inside withAndroidConfigFile since it is a simple file copying code.</p><p>Now let’s move into ios part. If you noted what I quoted from smile id documentation, copying the file is not enough for ios. It also asks to add the file for target. Doing that was bit tricky since there is no exact, well documented source anywhere in the internet as of now for the functions and methods that we can use while writing plugins. For that finally I had to go through the @expo/config-plugins library and read comments and understand the functionality of each methods available.</p><p>Let’s add the ios code also to copy-file-config.js</p><pre>const fs = require(&quot;fs&quot;);<br>const path = require(&quot;path&quot;);<br>const {<br>  withPlugins,<br>  withXcodeProject,<br>  withAndroidManifest,<br>  IOSConfig,<br>} = require(&quot;@expo/config-plugins&quot;);<br><br>const withMyConfigFile = (config, { src, iosDest, androidDest, groupName }) =&gt; {<br>  return withPlugins(config, [<br>    (config) =&gt; withIOSConfigFile(config, { src, dest: iosDest, groupName }),<br>    (config) =&gt; withAndroidConfigFile(config, { src, dest: androidDest }),<br>  ]);<br>};<br><br>//For ios<br>const withIOSConfigFile = (config, { src, dest, groupName }) =&gt; {<br>  return withXcodeProject(config, async (config) =&gt; {<br>    try {<br>      const sourcePath = path.resolve(__dirname, src); <br>      const destinationPath = path.resolve(<br>        config.modRequest.platformProjectRoot,<br>        dest<br>      );<br><br>      if (!fs.existsSync(sourcePath)) {<br>        throw new Error(`Source file not found at ${sourcePath}`);<br>      }<br>      //copy file to root directory<br>      fs.copyFileSync(sourcePath, destinationPath);<br><br>      const project = config.modResults;<br><br>      //Add file to target and copy bundle resources<br>      IOSConfig.XcodeUtils.addResourceFileToGroup({<br>        filepath: destinationPath,<br>        groupName: groupName,<br>        isBuildFile: true,<br>        project,<br>        verbose: true,<br>      });<br>    } catch (error) {<br>      console.error(`Error copying ${src} to ios:`, error.message);<br>      throw error;<br>    }<br>    return config;<br>  });<br>};<br><br>//For android<br>const withAndroidConfigFile = (config, { src, dest }) =&gt; {<br>  return withAndroidManifest(config, async (config) =&gt; {<br>    const sourcePath = path.resolve(__dirname, src); <br>    const destinationPath = path.resolve(<br>      config.modRequest.platformProjectRoot,<br>      dest<br>    );<br><br>    try {<br>      // Copy the file to the destination directory<br>      if (!fs.existsSync(sourcePath)) {<br>        throw new Error(`Source file not found at ${sourcePath}`);<br>      }<br><br>      const destDir = path.dirname(destinationPath);<br>      if (!fs.existsSync(destDir)) {<br>        fs.mkdirSync(destDir, { recursive: true });<br>      }<br><br>      fs.copyFileSync(sourcePath, destinationPath);<br>    } catch (error) {<br>      console.error(`Error copying ${src} to Android:`, error.message);<br>      throw error;<br>    }<br><br>    return config;<br>  });<br>};<br><br>module.exports = withMyConfigFile;</pre><p>If you notice withIOSConfigFile function, there we copy the file first and then add to target using following code snippet.</p><pre>const project = config.modResults;<br><br>IOSConfig.XcodeUtils.addResourceFileToGroup({<br>        filepath: destinationPath,<br>        groupName: groupName,<br>        isBuildFile: true,<br>        project,<br>        verbose: true,<br>      });</pre><ul><li><strong>Fetches the Xcode project</strong> (config.modResults).</li><li>Uses <strong>IOSConfig.XcodeUtils.addResourceFileToGroup</strong> to:</li><li>Add the copied file to the <strong>Xcode group</strong> (groupName).</li><li>Mark it as a <strong>build resource</strong>, so it’s included in the final app package<strong>(copy bundle resources)</strong>.</li><li>Prints logs (verbose: true) to debug if necessary.</li></ul><p>Before I find this addResourceFileToGroup function, I burned few midnights while trying to modify Xcode project object. It didn’t work.</p><p>Finally run npx expo prebuild commad which will generate ios and android directories with the changes.</p><h4>Final thoughts</h4><p>It was pretty interesting doing this with limited resources available to refer. If you want to write a different plugin please dig in to the @expo/config-plugins library bit and try to understand the functions available. The library is not documented anywhere and you cannot find everything you want <a href="https://docs.expo.dev/config-plugins/introduction/">expo documentation</a>. Found <a href="https://www.youtube.com/watch?v=5_IldjcRmj0">this</a> video useful though.</p><p>Hit on clap, share and comment to motivate me 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d43f4efdab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating GraphQL APIs with Strapi(Headless CMS) as backend]]></title>
            <link>https://krishanmadushankadev.medium.com/creating-graphql-apis-with-strapi-headless-cms-as-backend-a0685285b2dd?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0685285b2dd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[headless-cms]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[strapi]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 08:30:42 GMT</pubDate>
            <atom:updated>2023-06-24T06:35:10.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NrLdbDzQiY_b8a-7130BYQ.png" /></figure><p>If you want to create some REST APIs quickly without much coding knowledge you can use a Headless CMS tool.Here the word hedless gives the meaning <strong>no-head</strong> which is simillar to the meaning <strong>no-frontend</strong>.When using headless CMS tools you have to build the frontend with your own.Of course there are limitations with headless CMS but to implement project with some basic features even with authentication added, you can use a headless CMS tool. In this article I’ll be discussing about how to use a popular CMS tool called <a href="https://strapi.io/">Strapi</a> to create some GraphQL APIs.</p><h4>Create Project</h4><p>Run the following command in your terminal or cmd inside your project directory and select Quickstart when prompted.</p><pre>npx create-strapi-app@latest strapi-graphql</pre><p>Now project will be created and will strart running automatically in your browser in localhost:1337.It will open up the following screen for you to register as an Admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_Y7LuM8WjQurkEbDpq13w.png" /></figure><p>Enter your details and click <strong>Let’s start. </strong>Now you will be logged in to strapi dashboard.</p><h4>Main Strapi tabs to focus</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Qznpgo6rh4h1889C9rXiw.png" /></figure><ol><li>This is where you add data entries to the entities you created.</li><li>You create entities here with the properties you want. For example, Restaurant entity with name, location etc.</li><li>This is where all media files can be found.</li><li>External strapi plugins can be seen here.</li><li>Do strapi related configurations like adding authentication,create user roles, creating users with Admin access etc.</li></ol><h4>Create content types</h4><p>Click on <strong>Content-Type builder -&gt; Create new collection</strong> type and create your first entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rcRyl6jkUyHyQsCfoS3hA.png" /></figure><p>Enter entity name here.Then click continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ak-93ENu028Gem27PYLJiQ.png" /></figure><p>Now select a type for your first property of your entity. For food item <strong>Name</strong> we can select <strong>Text</strong> type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ar26o8EaFeSEk0eddf4rDA.png" /></figure><p>Enter the property name here.You can check Required if you want by going to <strong>ADVANCED SETTINGS</strong> tab.By clicking on <strong>Add another field</strong> button add more fields with relevant property type. I added Description and Image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8Eqh4dzDEDuRO8EB3L0DQ.png" /></figure><p>Click <strong>Save</strong>.Our entity is ready now. Let’s create another entity called Category which have a <strong>relationship</strong> with food item entity.<br>Follow the above steps and while creating the Category entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj6erDf_H1g3CQ0SEyUQYQ.png" /></figure><p>To have a relationship with Food Item, Select Relation type from the field types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sAbBhnjfa6FAePDEKbDYg.png" /></figure><p>Select the relationship type you want and click <strong>Finish</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTIR0q-GxGSgYJv4-tbApQ.png" /></figure><p>Click <strong>Save.</strong>Categoty entity also ready now.</p><h4>Adding Content to Entities</h4><p>Click on <strong>Content-Manager </strong>tab and click on relavant entity. Then click on <strong>Create new entry</strong> button.Then fill out the data for properties of each entity.Let’s create a category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMr5T3V-Xb8aE_rMV3L7jQ.png" /></figure><p>Since there are no data in food items entity you cannot select a relation here.Click <strong>Save </strong>and<strong> Publish.</strong></p><p>Let’s create a food item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8soLEVRPfdDJ6A3kR88Ig.png" /></figure><p>Click <strong>Save </strong>and<strong> Publish</strong>. Add some more data if needed.</p><h4>Adding permissions in public role</h4><p>There are mainly 2 roles created automatically namely <strong>Public</strong> and <strong>Authenticated</strong> which you can see if you navigate to Settings -&gt; Roles(under users and permissions plugin). We’ll be using Public role since we are not going to add authentication here. Click on public role and add permissions for each entity you created to create,read,update and delete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYHjWr6it9sH_CK5hZI-uQ.png" /></figure><p>Click <strong>Save.</strong></p><h4>Test REST API</h4><p>Open your favourite rest client and call the below endpoint to get food items.</p><p><a href="http://localhost:1337/api/food-items">http://localhost:1337/api/food-items</a></p><p>It will return a response like below.</p><pre>{<br>    &quot;data&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;attributes&quot;: {<br>                &quot;Name&quot;: &quot;Quinoa Salad with Hump Seeds&quot;,<br>                &quot;Description&quot;: &quot;rich in fibres.&quot;,<br>                &quot;createdAt&quot;: &quot;2023-06-23T07:00:24.829Z&quot;,<br>                &quot;updatedAt&quot;: &quot;2023-06-23T07:15:03.879Z&quot;,<br>                &quot;publishedAt&quot;: &quot;2023-06-23T07:15:03.876Z&quot;<br>            }<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;attributes&quot;: {<br>                &quot;Name&quot;: &quot;Chicken Submarine&quot;,<br>                &quot;Description&quot;: &quot;this is fast food&quot;,<br>                &quot;createdAt&quot;: &quot;2023-06-23T07:02:31.128Z&quot;,<br>                &quot;updatedAt&quot;: &quot;2023-06-23T07:14:57.824Z&quot;,<br>                &quot;publishedAt&quot;: &quot;2023-06-23T07:14:57.822Z&quot;<br>            }<br>        }<br>    ],<br>    &quot;meta&quot;: {<br>        &quot;pagination&quot;: {<br>            &quot;page&quot;: 1,<br>            &quot;pageSize&quot;: 25,<br>            &quot;pageCount&quot;: 1,<br>            &quot;total&quot;: 2<br>        }<br>    }<br>}</pre><p>This verifies our backend works fine now. You won’t see Image here you have to pass a query parameter populate[0]=Image to retrieve it.</p><h4>Configuring the backend for GraphQL</h4><p>To configure our Strapi backend for GraphQL we have to install a plugin.Open your project from terminal and run following command to install the plugin.</p><pre>npm run strapi install graphql</pre><p>If the above command fails, head over to <a href="https://www.npmjs.com/package/@strapi/plugin-graphql">this link </a>and install npm package directly. Now open our strapi project with your favoirite IDE and create and open <em>plugins.js</em> file inside <em>config</em> folder.Add the following code there.</p><pre>module.exports = {<br>  graphql: {<br>    config: {<br>      endpoint: &#39;/graphql&#39;,<br>      shadowCRUD: true,<br>      playgroundAlways: false,<br>      depthLimit: 7,<br>      amountLimit: 100,<br>      apolloServer: {<br>        tracing: false,<br>      },<br>    },<br>  },<br>};</pre><p>Then run following commands inside your project folder.</p><pre>npm run build<br>npm run develop</pre><p>Now, from browser load the <a href="http://localhost:1337/graphql">http://localhost:1337/graphql</a> url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7DwK6lrIH5zXQSgGRlG3g.png" /></figure><p>You will get the above console that you can run graphql queries.</p><h4>Running GraphQL queries</h4><pre>query getFoodItems{<br>    foodItems{<br>      data{<br>        id<br>        attributes{<br>          Name<br>          Description<br>          Image{<br>              data{<br>                  id<br>                  attributes{<br>                      name<br>                      formats<br>                  }<br>              }<br>          }<br>          category{<br>              data{<br>                  id<br>                  attributes{<br>                      Name<br>                  }<br>              }<br>          }<br>        }<br>      }<br>    }<br>}</pre><p>If you run the above query you’ll get following response.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;foodItems&quot;: {<br>      &quot;data&quot;: [<br>        {<br>          &quot;id&quot;: &quot;1&quot;,<br>          &quot;attributes&quot;: {<br>            &quot;Name&quot;: &quot;Quinoa Salad with Hump Seeds&quot;,<br>            &quot;Description&quot;: &quot;rich in fibres.&quot;,<br>            &quot;Image&quot;: {<br>              &quot;data&quot;: [<br>                {<br>                  &quot;id&quot;: &quot;1&quot;,<br>                  &quot;attributes&quot;: {<br>                    &quot;name&quot;: &quot;chicken_sandwhich.jpeg&quot;,<br>                    &quot;formats&quot;: {<br>                      &quot;thumbnail&quot;: {<br>                        &quot;name&quot;: &quot;thumbnail_chicken_sandwhich.jpeg&quot;,<br>                        &quot;hash&quot;: &quot;thumbnail_chicken_sandwhich_c95e23349f&quot;,<br>                        &quot;ext&quot;: &quot;.jpeg&quot;,<br>                        &quot;mime&quot;: &quot;image/jpeg&quot;,<br>                        &quot;path&quot;: null,<br>                        &quot;width&quot;: 208,<br>                        &quot;height&quot;: 156,<br>                        &quot;size&quot;: 9.77,<br>                        &quot;url&quot;: &quot;/uploads/thumbnail_chicken_sandwhich_c95e23349f.jpeg&quot;<br>                      }<br>                    }<br>                  }<br>                }<br>              ]<br>            },<br>            &quot;category&quot;: {<br>              &quot;data&quot;: {<br>                &quot;id&quot;: &quot;1&quot;,<br>                &quot;attributes&quot;: {<br>                  &quot;Name&quot;: &quot;Good Fibres&quot;<br>                }<br>              }<br>            }<br>          }<br>        },<br>        {<br>          &quot;id&quot;: &quot;2&quot;,<br>          &quot;attributes&quot;: {<br>            &quot;Name&quot;: &quot;Chicken Submarine&quot;,<br>            &quot;Description&quot;: &quot;this is fast food&quot;,<br>            &quot;Image&quot;: {<br>              &quot;data&quot;: [<br>                {<br>                  &quot;id&quot;: &quot;2&quot;,<br>                  &quot;attributes&quot;: {<br>                    &quot;name&quot;: &quot;Submarine.jpg&quot;,<br>                    &quot;formats&quot;: {<br>                      &quot;thumbnail&quot;: {<br>                        &quot;name&quot;: &quot;thumbnail_Submarine.jpg&quot;,<br>                        &quot;hash&quot;: &quot;thumbnail_Submarine_a642e264d5&quot;,<br>                        &quot;ext&quot;: &quot;.jpg&quot;,<br>                        &quot;mime&quot;: &quot;image/jpeg&quot;,<br>                        &quot;path&quot;: null,<br>                        &quot;width&quot;: 235,<br>                        &quot;height&quot;: 156,<br>                        &quot;size&quot;: 7.97,<br>                        &quot;url&quot;: &quot;/uploads/thumbnail_Submarine_a642e264d5.jpg&quot;<br>                      },<br>                      &quot;small&quot;: {<br>                        &quot;name&quot;: &quot;small_Submarine.jpg&quot;,<br>                        &quot;hash&quot;: &quot;small_Submarine_a642e264d5&quot;,<br>                        &quot;ext&quot;: &quot;.jpg&quot;,<br>                        &quot;mime&quot;: &quot;image/jpeg&quot;,<br>                        &quot;path&quot;: null,<br>                        &quot;width&quot;: 500,<br>                        &quot;height&quot;: 332,<br>                        &quot;size&quot;: 25.7,<br>                        &quot;url&quot;: &quot;/uploads/small_Submarine_a642e264d5.jpg&quot;<br>                      }<br>                    }<br>                  }<br>                }<br>              ]<br>            },<br>            &quot;category&quot;: {<br>              &quot;data&quot;: {<br>                &quot;id&quot;: &quot;2&quot;,<br>                &quot;attributes&quot;: {<br>                  &quot;Name&quot;: &quot;Fast food&quot;<br>                }<br>              }<br>            }<br>          }<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>You can run mutations to update,delete or create food items or categories on your preference.</p><p>Thanks for reading. Your feedback is appreciated. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0685285b2dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Apple HealthKit — Swift]]></title>
            <link>https://krishanmadushankadev.medium.com/integrating-apple-healthkit-swift-8863d9784f45?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8863d9784f45</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[apple-healthkit]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 16:55:19 GMT</pubDate>
            <atom:updated>2023-01-04T04:44:23.691Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating Apple HealthKit — Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-hOD8xRHCBkoRwf7zPTQ8w.png" /></figure><p>Apple comes with nice app on iphones called <strong>Health </strong>which collects health and fitness data from your iPhone, the built-in sensors on your Apple Watch, compatible third-party devices, and apps that use HealthKit. With this apple ships <strong>Apple Healthkit</strong> which facilitates thirdparty apps, accessing and sharing health and fitness data while maintaining the user’s privacy and control.This article guides you in integrating the apple healthkit with your ios native mobile app and writing some queries to read user’s health data.</p><p>I’ll be using Xcode 14.0.1 while implementing the sample app here.</p><h4>Adding HealthKit to your app</h4><ul><li>Openup Xcode application in your mac and create a new ios project (HealthkitIntegration) with SwiftUI.(Using SwiftUI is not mandatory you can use UIKit as well with your requirement)</li><li>Select your project name in Xcode and click on <strong>Signing and Capabilities </strong>tab.</li><li>Then click on <strong>+ Capability.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0CXf_bobCfMBoBTNDJmyw.png" /></figure><ul><li>Now serch for healthkit in the dilog appeared and click on HealthKit from search results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DST-IbY5ZIu-eSv4fHlD8Q.png" /></figure><ul><li>Now you will see that healthkit has been added to your project. Next go to <strong>info </strong>tab in same screen and add <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nshealthshareusagedescription"><strong>NSHealthShareUsageDescription</strong></a> under Custom iOS Target Properties.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Csb7jAGQwFzJzNSO85XD1g.png" /></figure><p>Here I have added message to the user that explains why the app requested permission to read samples from the HealthKit store. If you want to add write permission to apple health, you must add <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nshealthupdateusagedescription"><strong>NSHealthUpdateUsageDescription</strong></a><strong> </strong>similarly. Since I am going to write queries only to read data in this artivle I’ll add only NSHealthShareUsageDescription permission.</p><h4>Request permission from apple health to access or share a by user’s thirdparty app</h4><p>Open <em>HealthkitIntegrationApp.swift</em> file which is the entry file for our project. Write the following code there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7b8af9030b0e322ab7cc19cb5216ea7/href">https://medium.com/media/f7b8af9030b0e322ab7cc19cb5216ea7/href</a></iframe><ul><li>Line 2 — Import HealthKit into your file.</li><li>Line 9 to 13 — Inside the init()<em> </em>function of HealthkitIntegrationApp struct check whether helathkit is available in the device and if availble instantiate HKHealthStore<em> </em>class.Then execute requestHealthkitPermissions()<em> </em>function.</li><li>Line 17 to 21 — Inside requestHealthkitPermissions()<em> </em>function first we create the set of data types that we want to request permission. Here I have added asking permission for reading heart rate, step count and sleep analysis.There are lot of data types available with apple helath and here I have use categotyType and quantityType only. For more data types refer <a href="https://developer.apple.com/documentation/healthkit/data_types">this</a>. These quantityType<em> </em>can be divided into 2 other parts called descrete and cumulative types. With descrete types we can query for Average, min and max(ex — : average,min or max heart rate of the day) while with cumulative type we can query for cumulative sum(ex — : total step count within a week)</li><li>Line 23 to 25 — <a href="https://developer.apple.com/documentation/healthkit/hkhealthstore/1614152-requestauthorization">Requesting permission</a> for the declared types. For read permission pass types under read: parameter and for save and update permission pass types under toShare<em>:</em> parameter. Since I am not going to write any data using my app to health, I pass nil for toShare: parameter.</li><li>Line 30 — healthStore object is added to the environment then we can use it in ContentView screen.</li><li>Line 35 — HKHealthStore must conform ObservableObject to be able to put healthStore to the environment.</li><li>If you run the application you can see the below screen with permission request.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*PR0lbIcCaJKJpxQ0gNi_jg.png" /></figure><ul><li>Note that if you deny the permission also you will get “Success” printed since this success response is not about whether user granted permission. It is about was apple health successfully promted user to give permission. For more clarification about this refer <a href="https://stackoverflow.com/questions/33018445/how-to-check-if-healthkit-has-been-authorized#:~:text=You%20are%20misinterpreting%20what%20the%20success%20flag%20means%20in%20this%20context.%20When%20success%20is%20true%2C%20all%20that%20means%20is%20that%20iOS%20successfully%20asked%20the%20user%20about%20health%20kit%20access.%20It%20does%20NOT%20mean%20that%20they%20responded%20to%20that%20question%20with%20a%20%27yes%27">this</a>. There is a function called authorizationStatus to check authorization status but ,</li></ul><blockquote>This method checks the authorization status for saving data.</blockquote><blockquote>To help prevent possible leaks of sensitive health information, your app cannot determine whether or not a user has granted permission to read data. If you are not given permission, it simply appears as if there is no data of the requested type in the HealthKit store. If your app is given share permission but not read permission, you see only the data that your app has written to the store. Data from other sources remains hidden.</blockquote><blockquote>— healthkit documentation</blockquote><h4>Writing queries to read data</h4><p>There are lot of queries that we can use with apple healthkit but this article will cover only 3 types of queries that are used very commonly.</p><p><strong>HKSampleQuery</strong></p><p>The sample query returns sample objects that match the provided type and predicate. You can provide a sort order for the returned samples, or limit the number of samples returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/696418e5be626a8199753e37fd7e1415/href">https://medium.com/media/696418e5be626a8199753e37fd7e1415/href</a></iframe><p>Above readHeartRate() function will print all heart rate values recorded in last 24 hours.</p><ul><li>Line 24 — Defining the type that we want to query</li><li>Line 25 — Defininf in which way we want to sort the data. Here I want to sort by date in acending order.</li><li>Line 26 to 30 — Defining the query with the relavant parameters.Since I want to get data in last 24 hrours I should create the predicate for it. get24hPredicate() function will return the predicate we want.For limit: you can limit the number of results by passing an Int value for this. Passing HKObjectQueryNoLimit won’t have limit.</li><li>Line 37 — Read the value with relavant units.Heart beat will have “count/time” units.Read more about different units from <a href="https://developer.apple.com/documentation/healthkit/hkunit">here</a>.</li><li>Line 42 — Executing the query to retrieve data.Once the query is executed it will call the resultsHandler closure where we handle the result data.</li></ul><p><strong>HKStatisticsQuery</strong></p><p>Statistics queries calculate common statistics over the set of matching samples. You can use statistical queries to calculate the minimum, maximum, or average value of a set of discrete quantities, or use them to calculate the sum for cumulative quantities. Keep in mind that <strong>you can use statistics queries with quantity samples only.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a12f0ea29cfc808aac365feb51e36427/href">https://medium.com/media/a12f0ea29cfc808aac365feb51e36427/href</a></iframe><p>Above readTotalStepCount() function will read the total step count in last 24 hours. Note that we use statistics query since we want to get cumulative sum.Similarly we can get Avg,Min and Max values for descrete types like heart rate,blood glucose etc.</p><p>Let’s go through the code and the simillar code snippets that comes from HKSampleQuery won’t be repeated.</p><ul><li>Line 6 to 8 — Iinitializing HKStatisticsQuery. Since we want to get the sum of steps in last 24 hours, predicate will be set for last 24hrs and options: will be HKStatisticsOptions.cumulativeSum . We pass HKStatisticsOptions.separateBySource if we want to get the total step counts recorded by different sources like apple watch and iphone.</li><li>Line 9 — Read the value with count units. You can get the relavant unit by visiting the apple healthkit documentation for <a href="https://developer.apple.com/documentation/healthkit/hkquantitytypeidentifier/1615548-stepcount">relavant data type</a>.</li></ul><p><strong>HKStatisticsCollectionQuery</strong></p><p>Statistics collection queries are often used to produce data for graphs and charts. For example, you might create a statistics collection query that calculates the total number of steps for each day or the average heart rate for each hour. Again, <strong>you can only use statistics collection queries with quantity samples.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/935b794f733df39584464c1cc012a0f1/href">https://medium.com/media/935b794f733df39584464c1cc012a0f1/href</a></iframe><p>Above readHourlyTotalStepCount() function will calculate total step count for each hour in last 24 hours. Note that we get an array of total step counts for each hour.</p><ul><li>Line 6 to 7 — Defining the interval that we want data.Since I want total step count for each hour I am setting interval.hour = 1 .</li><li>Line 9 to 10 — When we initialise the query we need to specify an anchor. The anchor defines a moment in time where we are to calculate our samples from. Here since I have set the minute: 55the hours will be like 9:55–10:55 AM, 10:55–11:55 AM etc.</li><li>Line 18 to 23 — initialResultsHandler will get the data after executing the query and then we have the option of enumerating through the statistics. There we’ll pass a date before 24hrs from now as from: param and date now as to: param.</li></ul><p>P.S — Note that above queries run asynchronously by apple healthkit. We don’t need to put them inside a asynchronous block.</p><p>Find the completed code from <a href="https://github.com/KrishanMadushanka/AppleHealthkitIntegration">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8863d9784f45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Stripe sdk with React Native - part III -Refunding]]></title>
            <link>https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-react-native-part-iii-refunding-a02bf50163a6?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a02bf50163a6</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[refund]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 14:00:16 GMT</pubDate>
            <atom:updated>2022-09-27T14:01:33.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Stripe Refunding React Native Node" src="https://cdn-images-1.medium.com/max/710/1*5D5dBR_OQVH7Gwd6h8OABQ.png" /></figure><p>This is the part III of article series on integrating Stripe sdk with React Native.Before reading this article I kindly invite you to read my previous articles on integrating Stripe sdk with React Native.</p><ul><li><a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002">Integrating Stripe sdk with React Native - part I - Accept a payment</a></li><li><a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-react-native-part-ii-multiparty-payments-a2d094d1a647">Integrating Stripe sdk with React Native - part II - Multiparty payments</a></li></ul><p>These 2 articles will guide you on how to accept a payment and how to handle multiparty payments with stripe. To discuss about refunding you should have the prior knowledge about Stripe’s,</p><ul><li>Payment intents</li><li>Accepting payments</li><li>Connected account types</li><li>Charge types</li></ul><p>We’ll be using a node backend and react native front end. To know how to setup those environments refer my first article on <a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002">accept a payment</a>.</p><p>Refunds can be issued using the <a href="https://stripe.com/docs/api">API</a> or the <a href="https://dashboard.stripe.com/test/dashboard">Dashboard</a> and are processed immediately. When issued, refunds can’t be canceled.</p><p>To refund a payment using the API, create a refund and provide the ID of the charge or payment intent to be refunded.</p><p>When you use a payment intent to collect payment from a customer, Stripe creates a <a href="https://stripe.com/docs/api/charges/object">charge</a> behind the scenes. To refund the customer’s payment after the payment intent has succeeded, <a href="https://stripe.com/docs/api#create_refund">create a refund</a> using the payment intent, which is equivalent to refunding the underlying charge. You can also optionally refund part of their payment by specifying an amount.</p><h4>Refund using payment intent</h4><p>We should expose a rest api for this and we’ll be using previuos node codebase for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01acef47f906edc4ddef59371732c2da/href">https://medium.com/media/01acef47f906edc4ddef59371732c2da/href</a></iframe><p>You should keep track of payment intent ids you created in your db to issue a refund using payment intent id.Optionally you can specify an amount also.</p><pre>const refund = await stripe.refunds.create({<br>  payment_intent: &#39;pi_Aabcxyz01aDfoo&#39;,<br>  amount: 1000,<br>});</pre><p><em>You can issue more than one refund against a charge, but you can’t refund a total greater than the original charge amount.</em></p><p>We should call the exposed API from frontend to complete the refund.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ecbc3e88fc83685df1f6757abac3ec5/href">https://medium.com/media/2ecbc3e88fc83685df1f6757abac3ec5/href</a></iframe><h4>Refund using dashboard</h4><ul><li>Find the payment to be refunded in the <a href="https://dashboard.stripe.com/payments">payments </a>tab of the dashboard.</li><li>Click the ••• icon to the right of the charge. From the resulting menu, select <strong>Refund payment</strong>.</li></ul><figure><img alt="Stripe Refunding React Native Node" src="https://cdn-images-1.medium.com/max/1024/1*BQ-k62fhhF3xLD0vZvsrvA.png" /></figure><ul><li>By default, you’ll issue a full refund. For a partial refund, enter a different amount to be refunded.</li><li>Select a reason for the refund. If you select Other, you must provide an explanatory note that is attached to the refund.</li></ul><figure><img alt="Stripe Refunding React Native Node" src="https://cdn-images-1.medium.com/max/445/1*9NPIeGlo1E_blu9XUdTzjw.png" /></figure><ul><li>Click <strong>Refund</strong>.</li></ul><p>You can go to the specific payment from Dashboard and and click Refund there also.</p><figure><img alt="Stripe Refunding React Native Node" src="https://cdn-images-1.medium.com/max/1024/1*_5oWNl_WHBL7pMjuq5uBOQ.png" /></figure><h4>Refunding multiparty payments</h4><p>For multiparty payments refunding differs from each other on the charge type.To get an understanding about multiparty payments and charge types read <a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-react-native-part-ii-multiparty-payments-a2d094d1a647">previous article</a>.</p><p><strong>Refunding a direct charge</strong></p><p>To refund a direct charge on a connected account, perform a create refund request using your platform’s secret key while <a href="https://stripe.com/docs/connect/authentication#stripe-account-header">authenticated</a> as the connected account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e45e20c7a5dfc6a31d2bf15d75219e21/href">https://medium.com/media/e45e20c7a5dfc6a31d2bf15d75219e21/href</a></iframe><p>We can get above charge id by calling <a href="https://stripe.com/docs/api/charges/list#:~:text=%3A%20null%0A%7D-,List%20all%20charges,-Returns%20a%20list">list all charges API</a> with <em>payment_intent</em> specified.The API will return all the charges made on that payment intent<strong><em>(</em></strong><em>For testing purposes you can directly go to dashboard and click on specific payment-&gt;copy charge id from there</em><strong><em>).</em></strong>If we want to refund the application fee also, we can set that parameter true. Refunded amount will be deducted from connected accoun’s balance.</p><p><strong>Refunding a destination charge</strong></p><p>Let’s write an API in backend side for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98afb532bff52d56d7c98f10aed517d1/href">https://medium.com/media/98afb532bff52d56d7c98f10aed517d1/href</a></iframe><p>Here also we can get the <em>charge id</em> using the API that we discussed in refunding a direct charge.By default the destination account keeps the funds that were transferred to it, leaving the platform account to cover the negative balance from the refund. To pull back the funds from the connected account to cover the refund, set the <em>reverse_transfer</em> parameter to <em>true</em> when creating the refund. If we want to refund the application fee also, we can set <em>refund_application_fee</em> parameter true.</p><p><strong>Refunding separate charges and transfers</strong></p><p>Charges created on your platform can be refunded with charge id. However, refunding a charge has no impact on any associated transfers. It is up to your platform to reconcile any amount owed back to your platform by reducing subsequent transfer amounts or by reversing transfers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b964060a4c1d33a48ec2a463e1053840/href">https://medium.com/media/b964060a4c1d33a48ec2a463e1053840/href</a></iframe><p>Here also we can get the <em>charge id</em> using the API that we discussed in refunding a direct charge.</p><p>For all 3 types of charges you can do refunding through dashboard also.</p><p>Thanks for reading. 😊 Your feedback is appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a02bf50163a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Stripe sdk with React Native - part II - Multiparty payments]]></title>
            <link>https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-react-native-part-ii-multiparty-payments-a2d094d1a647?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d094d1a647</guid>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[multi-party]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 08:34:20 GMT</pubDate>
            <atom:updated>2022-09-22T12:03:33.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*ITp6-l0sel87pdXkvB1Wfw.png" /></figure><p>As I discussed <a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002">integrating stripe sdk with react native</a> in one of my previous articles, this time I decided to write on how to do multiparty payments using stripe. The knowledge from the <a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002">previous article</a> is useful here since we use the stripe payment sheet here also to complete the payment by entering card details.</p><h4>What are multiparty payments ?</h4><p>Stripe multiparty payment is used to route payments between multiple parties. For example consider a online hotel booking system where hotel owners can come into the platform and register while people can book hotels through the platform. Once a customer books a hotel and makes the payment through the platform,the payment should split and a part of the payment should go to hotel and another part(may be a percentage from the payment) to the platform (service provider). To route this kind of payments stripe has came up with <a href="https://stripe.com/docs/connect">stripe connect</a><strong> </strong>which we are going to integrate now with a react native application using node.js backend.</p><h4>Stripe connect</h4><p>To split the paymet and debit relavant amount we need to onboard users to stripe with their business and bank details. Stripe connect is used to handle multiparty payments and there are 3 types of connected accounts that we can create while onboarding users to stripe,</p><p><a href="https://stripe.com/docs/connect/accounts#standard-accounts"><strong>Standard account:</strong></a><strong> </strong>A conventional Stripe account controlled directly by the account holder (that is, your platform’s user)and has a relationship with Stripe, is able to log into the Stripe Dashboard, can process charges on their own, and can disconnect their account from your platform. Once the user is onboarded, user can login to their account using their credentials.</p><p><a href="https://stripe.com/docs/connect/accounts#express-accounts"><strong>Express account:</strong></a> After onboarded with this type of connected account the platform can manage payout schedules, customize the flow of funds, and control branding. An express dashboard is also available for express accounts, but you need to get a url from platform to view this.</p><p><a href="https://stripe.com/docs/connect/accounts#custom-accounts"><strong>Custom account:</strong></a> This account is almost completely invisible to the account holder and Stripe has no direct contact with them. Custom accounts require the most integration effort and are suitable for platforms who want to control the entire user experience.</p><p>The platform’s stripe account can see all these accounts under connected accounts of platform.</p><p>To start the coding you need to setup a node backend and react native application with stripe sdk integrated. For that kindly follow my previous article <a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002">integrating stripe sdk with react native</a>.</p><h4><strong>Account creation (onboarding users)</strong></h4><p>Following prerequisites is needed to be completed with the platform’s stripe account before creating connected accounts.</p><ol><li><a href="https://dashboard.stripe.com/connect/tasklist">Register your platform</a>.</li><li>Add business details to <a href="https://dashboard.stripe.com/account/onboarding">activate your account</a>.</li><li>Complete your <a href="https://dashboard.stripe.com/connect/settings/profile">platform profile</a>.</li><li><a href="https://dashboard.stripe.com/settings/connect">Customize brand settings</a>. Adding a business name, icon, and brand color is required for Connect Onboarding.</li></ol><p>I am not going to go through above prerequisites since they are pretty straightforward once you go to the relavant web pages linked above.</p><p>To get a user onboarded, we need to create an account in stripe with the type. Then with that account id created, we generate a link where the user can load into browser and enter their business and bank details.</p><p>To generate account creation link we should write rest APIs in backend and return account link to frontend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/586416d92029af72069761bc6fcb03a4/href">https://medium.com/media/586416d92029af72069761bc6fcb03a4/href</a></iframe><p>I have written 3 APIs above which differs each other on the account type. In every API we use 2 common APIs provided by stripe namely <a href="https://stripe.com/docs/api/accounts/create">accounts API</a> and <a href="https://stripe.com/docs/api/account_links">accountLinks API</a>.</p><p>If you’ve already collected information for your connected accounts, you can prefill that information on the account object for the user at account creation and it won’t be collected again in the onboarding flow. Any information on the account can be prefilled, including company or individual information, external account information, and more.For more details refer <a href="https://stripe.com/docs/api/accounts/create">accounts API</a>.</p><p>We must save the account id in our db to make payments in future on that account.</p><p><strong>return_url<br></strong>Stripe issues a redirect to this URL when the user completes the Connect Onboarding flow. We can use a <a href="https://reactnavigation.org/docs/deep-linking/">deep link</a> here to navigate back to the app but url schemes are not working since account creation API throws error. In test mode we can use http but in live mode we must use https universal link.</p><p><strong>refresh_url<br></strong>Your user redirects to the refresh_url in these cases:</p><ul><li>The link expired (a few minutes went by since the link was created)</li><li>The user already visited the link (they refreshed the page, or clicked back or forward in the browser)</li><li>Your platform is no longer able to access the account</li><li>The account has been rejected</li></ul><p>Your refresh_url should trigger a method on your server to call <a href="https://stripe.com/docs/api/account_links">Account Links</a> again with the same parameters, and redirect the user to the Connect Onboarding flow to create a seamless experience.</p><p>For expres and custom accounts you need to request <a href="https://stripe.com/docs/connect/account-capabilities">capabilities</a> while creating the account.For standard accounts you will get all the capabilities automatically. The capabilities you request for a connected account determine the information you need to collect for that account.</p><p>Now you need to call above APIs from frontend(React native), get the account link and open it with phone browser to get user onboarded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d442c377bdb495378ee307e66fb06e8/href">https://medium.com/media/5d442c377bdb495378ee307e66fb06e8/href</a></iframe><p>You will see a similar screen as follows once link is opened with mobile browser which starts the user onboarding flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*zjToTBZDFf27se6llMpBzQ.jpeg" /></figure><h4>Receive payments</h4><p>Now to receive a payment for the connected account a user should make a payment on that account. For that we have 3 charge types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XTyNuMETXEK7fdwCkK3Kw.png" /><figcaption>Captured from stripe documentation.</figcaption></figure><p>Direct charges are recommended to use with standard accounts while other 2 charge types are recommended to use with express and custom accounts by stripe.</p><p><strong>Create a direct charge<br></strong>We have to create the payment intent in backend side with connected stripe account, amount, application fee and currency.Application fee is the amout that goes to service provider’s (platform) account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ce4c62b5beb41517fa404aacc34e9b1/href">https://medium.com/media/0ce4c62b5beb41517fa404aacc34e9b1/href</a></iframe><p>From the frontend we should proceed the payment as we discussed in <a href="https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002">previous article</a>.</p><p>You have to add connected account’s id in <em>StripeProvider</em> to perform a direct charge on that account as follows.</p><pre>&lt;StripeProvider stripeAccountId=&#39;CONNECTED_STRIPE_ACCOUNT_ID&#39; publishableKey={publishableKey}&gt;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd5ad604fcbb1bb76690483b0832120a/href">https://medium.com/media/bd5ad604fcbb1bb76690483b0832120a/href</a></iframe><p>Once you call <strong><em>initializePaymentSheet()</em></strong><em>, </em>backend returns the <em>client_secret </em>to the frontend and with that we initialize payment sheet. Then to present the payment sheet to the user to enter card details call <strong><em>openPaymentSheet()</em></strong>.</p><p><strong>Direct charge flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrGzonRaiF6hnTuf60cegw.png" /><figcaption>Captured from stripe documentation.</figcaption></figure><p>Note that stripe fee is deducted from connected accounts amount.</p><p><strong>Create a destination charge<br></strong>We have to create the payment intent with connected transfer data, amount, application fee and currency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e32ad890026d0479c295490b95efbc/href">https://medium.com/media/e7e32ad890026d0479c295490b95efbc/href</a></iframe><p>Proceeding payment with payment intent in the frontend doesn’t change.It’s similar to the direct charge implementation above.</p><p>you don’t need to add account id in <em>StripeProvider</em> since you can do destination charge with your platform account publishable key and secret key.</p><p><strong>Destination charge flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OCso2NrCOBrS0TTyyb5kg.png" /><figcaption>Captured from stripe documentation.</figcaption></figure><p>Note that stripe fee is deducted from platform account.</p><p><strong>Create separate charges and transfers<br></strong>With this you can make charges on your platform account on behalf of connected accounts, perform transfers separately, and retain funds in the process. Separate charges and transfers are recommended for Express or Custom accounts where you collect charges that can be a different amount than what’s paid out to your connected accounts. Here also we should write an API to create the payment intent with amount, currency, and transfer group.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5999cf89831a06630e26ecd09e2828c3/href">https://medium.com/media/5999cf89831a06630e26ecd09e2828c3/href</a></iframe><p>This payment intent is returned to the frontend, and we can complete the charge as we did in above direct charge scenario. But to transfer the payments to connected accounts we must write an API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f5f3abc8c876b76d1dd1dc8e2e10e28/href">https://medium.com/media/1f5f3abc8c876b76d1dd1dc8e2e10e28/href</a></iframe><p>With transfer group you can return all the transfers associated with that transfer_group.</p><pre>const transfers = await stripe.transfers.list({<br>    transfer_group: bookingId<br>})</pre><p><strong>Separate charges and transfers flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMlg_VI__h05RP8pRrzYmg.png" /><figcaption>Captured from stripe documentation.</figcaption></figure><p>Unlike the other 2 scenarios, with separate charges you do not transfer the amount to connected accounts when you make the payment.Stripe fee also deducted from platform account. You must have positive stripe balance to do the transfers to connected accounts.</p><p>You can see all your connected accounts under connect tab of platform account. Accounts that successfully completed the onboarding flow can be seen with status “<strong>complete</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0lTq0N201f3nU25NG_jfA.png" /><figcaption>connected accounts list</figcaption></figure><p>You can click on each account and go to a detailed view.</p><p>All the payments come to the <strong>platform account or connected standard</strong> account can be seen under payments tab of relavant account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYfvu7eV7DrMB6HHoNxQKg.png" /><figcaption>Payments of the stripe account.</figcaption></figure><p>To view payments of express accounts you can use the <a href="https://stripe.com/docs/connect/express-dashboard">express dashboard</a> or go to conneted account’s detailed view from platform account.</p><p>All the application fees that collected to the platform can be seen under “collected fees” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ArVR4rXo-gpQxPTNNaOtA.png" /></figure><p>Hit on clap, share and comment if this helped.Your feedback is appreciated. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d094d1a647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Stripe sdk with React Native - part I - Accept a payment]]></title>
            <link>https://krishanmadushankadev.medium.com/integrating-stripe-sdk-with-a-react-native-application-5bd3dc462002?source=rss-a2cbb9fb735e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd3dc462002</guid>
            <category><![CDATA[stripe-integration]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[stripe-payment]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Krishan Madushanka]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 13:54:26 GMT</pubDate>
            <atom:updated>2022-09-22T11:50:27.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*0_-ATwnHH-sAPYKSKrr-8g.png" /></figure><p>Since Stripe is a popular and trusted payment gateway across the world and since it is used among most mobile applications which process payments, I guess writing an article on integrating Stripe sdk with a react native application will be worth.Also I am not going to dig deep in to stripe and I’ll be implementing a basic payment using Stripe sdk here.</p><p>First you need to go <a href="https://dashboard.stripe.com/register">this</a> url and create a account in stripe.That is pretty straightforward and I am not going to guide it here.</p><p>Then create a react native project and add stripe sdk using following commands</p><pre>npx react-native init StripeProject<br>npm install @stripe/stripe-react-native</pre><p>Open your project from your favourite IDE and open <strong>App.js</strong> and add following code.Follow <a href="https://github.com/stripe/stripe-react-native">this</a> guide also whenever needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61d81b60e56723db59a36d5edb1fb706/href">https://medium.com/media/61d81b60e56723db59a36d5edb1fb706/href</a></iframe><p>Here the publishable key is a key that you should take from your stripe account that you created.(Storing this key also in backend and retrieving it from there is more secure than storing it with frontend code)Go to dashboard in your stripe account, turn on test mode from top right <strong>Test</strong> button and copy publishable key from there.</p><p>Now we need a backend also to do stripe integration because we do payment intent creation in backend.You will understand what is <strong><em>payment intent</em></strong> in a second. I will be using node express here to implement the backend.</p><p>Create a new folder named server, navigate into the folder, run npm init -y, and follow the instructions to create a new Node app. Then, run npm i express dotenvto install <strong>express</strong> framework and <strong>dotenv </strong>which is a lightweight npm package that automatically loads environment variables from a .env file into the process.env object <strong>(</strong><em>environment variables are a great way to securely and conveniently configure things that don’t change often, like URLs, authentication keys, and passwords</em><strong>)</strong>.</p><p>Install stripe also in backend using,</p><pre>npm install stripe --save</pre><p>Now create a file with name <strong>.env</strong> and add following code. Get the secret key also from the stripe dashboard.</p><pre>secret_key=&lt;your secret key here&gt;<br>PORT=8000</pre><p>Now lets write a rest api to create payment intent and customer id from backend and return the <strong>clientSecret </strong>and<strong> customer id </strong>which is needed to confirm the payment from front end. A p<a href="https://stripe.com/docs/api/payment_intents">aymentIntent</a>, Stripe uses this to represent your intent to collect payment from a customer, tracking your charge attempts and payment state changes throughout the process.</p><p>create file called server.js and add following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/223ae2e338ff73b28a27d11ad36f8515/href">https://medium.com/media/223ae2e338ff73b28a27d11ad36f8515/href</a></iframe><p>Here ve have exposed an api <strong><em>/create-payment-intent </em></strong>which creates a payment with 1299$ (Note you have to multiplay the value by 100 ,otherwise it’s 12.99$) and sends that client secret and customer id to front end.The amount is hardcoded in backend side but you can send it to backend through the api.Now from front end we should use this client secret and customer id to open the payment sheet with 1299$. Then we can enter our card details and confirm the payment from react native app. When a customer id is created we can reuse it and in a situation like we want to save card details under one customer we can reuse the customer id.</p><p>Now run the server in your localhost using command</p><pre>npm start</pre><p>Now in App.js file update the code as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae7971d6a67151ea321d7616e3d59d7f/href">https://medium.com/media/ae7971d6a67151ea321d7616e3d59d7f/href</a></iframe><p>In Above code ahen you run the app it will call <strong><em>initializePaymentSheet(); </em></strong>mehtod and it will call the backend api <strong><em>/create-payment-intent </em></strong>and initialize payment sheet with relavant parameters. once we click on <strong>Checkout </strong>button the app will open the payment sheet as follows</p><figure><img alt="xsxs" src="https://cdn-images-1.medium.com/max/1024/1*9sLPtpdD_LhYZARH3Z3VWg.png" /></figure><p>Here you can enter card details and click on pay to pay the amount.(you can use 4242 4242 4242 4242 test card number with any cvc and expiary date).After that go to payments tab in your stripe accout and verify the paymet is added there.</p><p>Similarly you can use<strong> </strong><a href="http://cardfield/"><strong>card field </strong></a>and <a href="https://stripe.dev/stripe-react-native/api-reference/index.html#CardForm:~:text=Const-,CardForm,-CardForm%3A"><strong>card form</strong></a><strong> </strong>instead of payment sheet which is coming from the bottom.</p><p>Final output —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*6yDOKUAWzRKrDzdC8KLRig.gif" /></figure><p><a href="https://github.com/KrishanMadushanka/Stripe-react-native">React native code</a><br><a href="https://github.com/KrishanMadushanka/Stripe-backend">Backend code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd3dc462002" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>