<?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 Tarik on Medium]]></title>
        <description><![CDATA[Stories by Tarik on Medium]]></description>
        <link>https://medium.com/@tarikfp?source=rss-9c9b54aeb0a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NGLaJbS7rzy9qwTG8-IqbQ.png</url>
            <title>Stories by Tarik on Medium</title>
            <link>https://medium.com/@tarikfp?source=rss-9c9b54aeb0a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:29:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tarikfp/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[Building a Live Activity Timer in Expo React Native]]></title>
            <link>https://levelup.gitconnected.com/building-a-live-activity-timer-in-expo-626b162f3e8d?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/626b162f3e8d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Fri, 02 May 2025 00:44:25 GMT</pubDate>
            <atom:updated>2025-06-01T16:51:29.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VfjKUrpnahwA6LjIQ58BXw.png" /></figure><p>Live Activities on iOS are a game changer, they let apps show real-time updates right on the Lock Screen or Dynamic Island. Naturally, I started imagining how cool it would be to have a workout timer running there, keeping users motivated without even unlocking their phones. But there was a catch: Live Activities are built with Apple’s native tools, like Swift and ActivityKit. That’s when I discovered a tool called <a href="https://github.com/EvanBacon/expo-apple-targets">expo-apple-targets</a> instead of writing entire modules from scratch, which made the process much easier than I expected. In this article, I’ll walk you through how I built a timer-based Live Activity for iOS, the steps I took, and what I learned along the way.</p><h3>Why Live Activities Got Me Obsessed</h3><p>Live Activities aren’t just a cool trick, they’re a game-changer for user engagement. Apple’s <a href="https://developer.apple.com/design/human-interface-guidelines/live-activities">Human Interface Guidelines</a> describe them as a way to deliver “current, glanceable information” for time-sensitive tasks. Picture a fitness app showing your plank time mid-workout, a food delivery app tracking your pizza’s journey, or a ride-sharing app updating your driver’s ETA, all right on the Lock Screen or, on iPhone 14 Pro and later, the Dynamic Island. It’s like giving users a VIP pass to your app’s most important updates without them needing to unlock their phone.</p><p>I wanted users to see their workout timer ticking up during a set, keeping them focused without forcing them to open the app. It’s the kind of polish that makes an app feel pro, and I was all in. But you can not handle all this without touching any native layer, so I knew I’d be diving into Swift and wrestling with Xcode. Discovering <a href="https://github.com/EvanBacon/expo-apple-targets">expo-apple-targets</a>, a package that bridges the gap between Expo’s JavaScript world and iOS’s native features. Huge props to <a href="https://medium.com/u/16b715de038f">Evan Bacon</a>, this tool took a daunting task and made it feel like a challenging but doable puzzle.</p><h3>The Big Picture: Live Activities in an Expo App</h3><p>Live Activities are an iOS-only party. They’re powered by ActivityKit, a Swift-based framework, which means you’re writing native code whether you like it or not. For an Expo app, this is like trying to convince a fish to climb a tree—it’s possible, but it’s gonna take some effort. expo-apple-targets steps in like a seasoned guide, providing a framework to create native modules and widget extensions without starting from scratch. It’s built on Expo’s module system (<a href="https://docs.expo.dev/modules/module-api/">Expo Modules API</a>), which lets you write native code in Swift and expose it to JavaScript, making the whole process feel less like a root canal.</p><h3>Setting Up the Project</h3><p>Getting started wasn’t exactly a walk in the park, but expo-apple-targets made it manageable. Here’s how I kicked things off:</p><ul><li><strong>Installing expo-apple-targets</strong>: A quick npm install expo-apple-targets got me rolling. The package’s README is a goldmine, guiding you through adding a widget extension in Xcode and updating app.json with the Live Activity entitlement (com.apple.developer.activitykit).</li><li><strong>Native Module Setup</strong>: I used Expo’s module system to create a Swift module that talks to ActivityKit. The <a href="https://docs.expo.dev/modules/module-api/">Expo Modules docs</a> emphasize defining clear function signatures and events, which helped me expose methods like startActivity to JavaScript without breaking a sweat.</li><li><strong>Widget Extension</strong>: This is where SwiftUI came in, letting me design the Live Activity’s look for the Lock Screen and Dynamic Island. expo-apple-targets provides a widget template, but I had to customize it to show a ticking timer and interactive buttons.</li><li><strong>Intents</strong>: These let users tap buttons on the widget to pause or resume the timer. expo-apple-targets simplifies intent setup, but I still had to debug a few misfires to get the notifications flowing right.</li></ul><h3>A timer that is updated every second?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq1a3rqsEIBCgTsAWdvgNQ.png" /><figcaption>A developer excitedly implements a one-second timer update, leading to chaotic system overload as the timer wreaks havoc. (<a href="https://openai.com/index/hello-gpt-4o/">Generated by gpt-4o</a>)</figcaption></figure><p>When I first tackled the timer, my brain said, “<em>Just update the Live Activity every second with the current time</em>.” Sounds straightforward, right? Wrong. I stumbled across a <a href="https://www.reddit.com/r/iOSProgramming/comments/18n12wh/how_does_this_app_achieve_to_update_its_live/?rdt=52173">Reddit thread</a> where devs were discussing the ability to update the Live Activity timer. The verdict was unanimous: updating every second is a disaster. It’s like trying to power a spaceship with a hamster wheel; it’ll move, but it’ll burn out fast. Constant updates hammer the CPU, drain the battery, making your app sluggish.</p><p>That Reddit thread was a wake-up call. I found SwiftUI’s Text(timerInterval:) in Apple’s <a href="https://developer.apple.com/documentation/swiftui/text/init(timerinterval:pausetime:countsdown:showshours:)">SwiftUI docs</a>, and it was a revelation. This view handles timer updates natively, ticking away without needing to refresh the entire Live Activity. It’s like outsourcing the boring stuff to iOS so you can focus on the fun parts.</p><p>So, I ditched the every-second-update plan and went with a startedAt/pausedAt approach. Here’s why it’s a winner:</p><ul><li><strong>Performance</strong>: Instead of firing off updates every second, I store the timer’s start time (startedAt) and pause time (pausedAt, if paused). The widget uses Text(timerInterval:) to show a live timer based on startedAt, and when paused, it displays a static time using pausedAt. This slashes API calls to near zero.</li><li><strong>Battery Efficiency</strong>: Frequent updates are a battery vampire. Letting SwiftUI handle the ticking keeps the app lean and users’ phones happy.</li><li><strong>API Compliance</strong>: Apple’s Live Activity APIs aren’t built for real-time spam. The startedAt/pausedAt setup plays nice with iOS’s expectations, reducing the chance of rate-limiting.</li><li><strong>Code Simplicity</strong>: Managing two timestamps is way easier than juggling a stream of updates. It keeps the code clean and my stress levels in check.</li></ul><p>This approach felt like finding a secret shortcut in a video game. The timer runs smoothly, looks great, and doesn’t hog resources. The Reddit thread (<a href="https://www.reddit.com/r/iOSProgramming/comments/18n12wh/how_does_this_app_achieve_to_update_its_live/?rdt=52173">here it is again</a>) deserves a medal for pointing me in the right direction.</p><h3>The Heart of the Live Activity</h3><p>I’m not gonna bore you with every line of code, let’s focus on the key snippets that make this timer tick. I’ll be sharing the full source code on GitHub at the end of the article.</p><h4>The LiveActivityAttributes Struct</h4><p>This struct is the backbone of the Live Activity, defining its data and how it evolves.</p><pre>struct LiveActivityAttributes: ActivityAttributes {<br>  public struct ContentState: Codable, Hashable {<br>    var startedAt: Date<br>    var pausedAt: Date?<br><br>    func getElapsedTimeInSeconds() -&gt; TimeInterval {<br>      if let pausedAt = pausedAt {<br>        return pausedAt.timeIntervalSince(startedAt)<br>      } else {<br>        return Date().timeIntervalSince(startedAt)<br>      }<br>    }<br>    func isRunning() -&gt; Bool {<br>      return pausedAt == nil<br>    }<br>    func getFormattedElapsedTime() -&gt; String {<br>      let elapsed = getElapsedTimeInSeconds()<br>      let totalSeconds = Int(elapsed)<br>      let hours = totalSeconds / 3600<br>      let minutes = (totalSeconds % 3600) / 60<br>      let seconds = totalSeconds % 60<br>      if hours &gt; 0 {<br>        return String(format: &quot;%d:%02d:%02d&quot;, hours, minutes, seconds)<br>      } else {<br>        return String(format: &quot;%d:%02d&quot;, minutes, seconds)<br>      }<br>    }<br>    func getFutureDate() -&gt; Date {<br>      return Date().addingTimeInterval(365 * 24 * 60 * 60)<br>    }<br>  }<br>  var activityName: String<br>  var activityIcon: String<br>}</pre><p>This is like the DNA of the Live Activity. The outer LiveActivityAttributes holds static stuff, activityName (e.g., “Workout”) and activityIcon (e.g., “RUNNING”) set when the activity starts. The inner ContentState is where the action happens, tracking startedAt (when the timer began) and pausedAt (when it’s paused, if at all). The helper methods are the real MVPs:</p><ul><li>getElapsedTimeInSeconds() calculates how long the timer’s been running, stopping at pausedAt if it’s paused, or using the current time if it’s active. This keeps the logic tight and reusable.</li><li>isRunning() is a simple check: if pausedAt is null, the timer’s live. It’s a clean way to avoid messy state checks elsewhere.</li><li>getFormattedElapsedTime() turns seconds into a nice “MM:SS” or “HH:MM:SS” string for the widget. I added hours support after realizing some users might do ultra-long workouts like marathons.</li><li>getFutureDate() sets a date a year out, which I feed to Text(timerInterval:) to let the timer run indefinitely without worrying about an end date.</li></ul><p>I love how this struct keeps things organized. It’s like a well-packed backpack — everything you need, nothing you don’t. The Codable and Hashable conformance makes it easy to serialize for updates and use in SwiftUI, which was a lifesaver when syncing state between the module and widget.</p><h4>Starting the Live Activity</h4><p>The startActivity function is where the magic begins, kicking off a new Live Activity.</p><pre>AsyncFunction(&quot;startActivity&quot;) { (activityName: String, activityIcon: String) -&gt; String in<br>    if #available(iOS 16.2, *) {<br>        await self.endAllActivities()<br>        self.startedAt = Date()<br>        self.pausedAt = nil<br>        if !ActivityAuthorizationInfo().areActivitiesEnabled {<br>            return &quot;&quot;<br>        }<br>        let attributes = LiveActivityAttributes(activityName: activityName, activityIcon: activityIcon)<br>        let contentState = LiveActivityAttributes.ContentState(startedAt: self.startedAt!, pausedAt: nil)<br>        do {<br>            let activity = try Activity.request(attributes: attributes, content: .init(state: contentState, staleDate: nil), pushType: nil)<br>            self.currentActivityId = activity.id<br>            self.sendTimerUpdateEvent()<br>            return activity.id<br>        } catch {<br>            throw error<br>        }<br>    }<br>    return &quot;&quot;<br>}</pre><p>This function is the spark that lights the fire. It’s exposed to JavaScript via Expo’s module system, letting my React Native app call it with a name and icon. Here’s what it does:</p><ul><li>It checks for iOS 16.2 or later Live Activities don’t exist before that.</li><li>It calls endAllActivities() to clear out any existing activities. iOS allows multiple Live Activities, but I wanted one at a time to avoid confusion.</li><li>It sets startedAt to the current time and clears pausedAt, prepping the timer to run.</li><li>It verifies that Live Activities are enabled (users can disable them in Settings, which threw me for a loop early on).</li><li>It builds a LiveActivityAttributes with the provided name and icon, and a ContentState with the start time.</li><li>It requests a new activity via Activity.request, which gives me an Activity object with a unique ID.</li><li>It stores the ID, fires an update event to JavaScript, and returns the ID so the app can track it.</li></ul><h4>Pausing the Timer</h4><p>Pausing the timer is handled by performPause, which updates the Live Activity’s state.</p><pre>private func performPause(activityId: String?) async -&gt; Bool {<br>    guard #available(iOS 16.2, *), self.pausedAt == nil else {<br>        return false<br>    }<br>    let targetId = activityId ?? self.currentActivityId<br>    guard let targetId = targetId else {<br>        return false<br>    }<br>    guard let activity = await self.findActivityById(targetId) else {<br>        return false<br>    }<br>    guard let currentStartedAt = self.startedAt else {<br>        return false<br>    }<br>    let now = Date()<br>    self.pausedAt = now<br>    let contentState = LiveActivityAttributes.ContentState(startedAt: currentStartedAt, pausedAt: self.pausedAt)<br>    await activity.update(using: contentState)<br>    self.sendTimerUpdateEvent()<br>    return true<br>}</pre><p>This is where the startedAt/pausedAt approach shines. When the user pauses the timer (either from the app or widget), this function:</p><ul><li>Checks that we’re on iOS 16.2 and the timer isn’t already paused (no double-pausing allowed).</li><li>Grabs the activity ID, falling back to currentActivityId if none is provided.</li><li>Finds the activity using findActivityById, which searches through active activities.</li><li>Sets pausedAt to the current time, freezing the timer.</li><li>Creates a new ContentState with the original startedAt and the new pausedAt.</li><li>Updates the activity with activity.update, telling the widget to show the paused time.</li><li>Sends an event to JavaScript to keep the app’s UI in sync.</li></ul><p>The logic here is all about precision every check (like pausedAt == nil) is there to prevent weird edge cases, like pausing a non-existent activity. I leaned on the <a href="https://docs.expo.dev/modules/overview/">Expo Modules docs</a> for event handling, using sendEvent to push updates to JavaScript. Early versions of this function didn’t validate startedAt, which led to some funky timer displays—lesson learned: always guard your state.</p><h3>The Lock Screen View</h3><p>The LockScreenLiveActivityView is what users see when their phone’s locked, and it’s gotta look sharp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*IZ1ZSG7_99jfTMBJosePGQ.png" /><figcaption>Lock Screen Live Activity</figcaption></figure><pre>struct LockScreenLiveActivityView: View {<br>    let context: ActivityViewContext&lt;LiveActivityAttributes&gt;<br>    var body: some View {<br>        ZStack {<br>            Color.black.opacity(0.8)<br>                .clipShape(RoundedRectangle(cornerRadius: 16))<br>            HStack(spacing: 16) {<br>                VStack(alignment: .leading, spacing: 12) {<br>                    HStack(spacing: 8) {<br>                        ActivityIcon(activityIcon: mapJSIconToSFSymbol(context.attributes.activityIcon),<br>                                    themeColor: .white,<br>                                    size: 18)<br>                        Text(context.attributes.activityName)<br>                            .font(.headline)<br>                            .foregroundColor(.white)<br>                    }<br>                    VStack(alignment: .leading, spacing: 4) {<br>                        if !context.state.isRunning() {<br>                            Text(context.state.getFormattedElapsedTime())<br>                                .font(.system(size: 34, weight: .semibold, design: .rounded))<br>                                .foregroundColor(.white)<br>                                .fontWeight(.medium)<br>                                .monospacedDigit()<br>                        } else {<br>                            Text(timerInterval: context.state.startedAt...context.state.getFutureDate(),<br>                                 pauseTime: nil,<br>                                 countsDown: false,<br>                                 showsHours: false)<br>                                .font(.system(size: 34, weight: .semibold, design: .rounded))<br>                                .foregroundColor(.white)<br>                                .fontWeight(.medium)<br>                                .monospacedDigit()<br>                        }<br>                    }<br>                }<br>                .frame(maxHeight: .infinity, alignment: .center)<br>                Spacer()<br>                VStack {<br>                    Spacer()<br>                    if context.state.isRunning() {<br>                        Button(intent: PauseIntent()) {<br>                            ZStack {<br>                                Circle()<br>                                    .fill(Color(hex: &quot;#007bff&quot;))<br>                                    .frame(width: 44, height: 44)<br>                                Image(systemName: &quot;pause.fill&quot;)<br>                                    .font(.system(size: 18, weight: .bold))<br>                                    .foregroundColor(.white)<br>                            }<br>                        }<br>                        .buttonStyle(PlainButtonStyle())<br>                    } else {<br>                        HStack(spacing: 8) {<br>                            Button(intent: CompleteIntent()) {<br>                                ZStack {<br>                                    Circle()<br>                                        .fill(Color(hex: &quot;#28a745&quot;))<br>                                        .frame(width: 44, height: 44)<br>                                    Image(systemName: &quot;checkmark&quot;)<br>                                        .font(.system(size: 16, weight: .bold))<br>                                        .foregroundColor(.white)<br>                                }<br>                            }<br>                            .buttonStyle(PlainButtonStyle())<br>                            Button(intent: ResumeIntent()) {<br>                                ZStack {<br>                                    Circle()<br>                                        .fill(Color(hex: &quot;#007bff&quot;))<br>                                        .frame(width: 44, height: 44)<br>                                    Image(systemName: &quot;play.fill&quot;)<br>                                        .font(.system(size: 18, weight: .bold))<br>                                        .foregroundColor(.white)<br>                                }<br>                            }<br>                            .buttonStyle(PlainButtonStyle())<br>                        }<br>                    }<br>                    Spacer()<br>                }<br>            }<br>            .padding(16)<br>        }<br>    }<br>}</pre><p>This is the visual heart of the Live Activity, and it’s where SwiftUI really flexes. The view is split into two sides:</p><ul><li><strong>Left Side</strong>: Shows the activity name, icon, and timer. If the timer’s running, Text(timerInterval:) does the heavy lifting, counting up from startedAt to a year out (thanks to getFutureDate). If paused, it displays a static time from getFormattedElapsedTime. The .monospacedDigit() modifier keeps the numbers crisp, and I tweaked the font to make it bold and readable.</li><li><strong>Right Side</strong>: Handles buttons. When running, there’s a blue pause button. When paused, you get a green checkmark to open the app and a blue play button to resume. Each button fires an intent, which the native module catches and processes.</li></ul><h3>Diving into the <a href="https://developer.apple.com/design/human-interface-guidelines/live-activities#The-Dynamic-Island">Dynamic Island</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*iqy0d6FZe9UU0Tce7qCDug.png" /><figcaption>Dynamic Island View</figcaption></figure><p>This snippet defines how the Live Activity appears in the Dynamic Island’s three modes: expanded (full view), compact (squeezed), and minimal (bare-bones).</p><pre>dynamicIsland: { context in<br>  DynamicIsland {<br>    DynamicIslandExpandedRegion(.leading) {<br>      VStack(alignment: .leading, spacing: 8) {<br>        HStack(spacing: 8) {<br>          ActivityIcon(activityIcon: mapJSIconToSFSymbol(context.attributes.activityIcon),<br>                      themeColor: .white,<br>                      size: 18)<br><br>          Text(context.attributes.activityName)<br>            .foregroundColor(.white)<br>            .font(.system(size: 16, weight: .semibold))<br>        }<br><br>        if !context.state.isRunning() {<br>          Text(context.state.getFormattedElapsedTime())<br>            .font(.system(size: 32, weight: .bold, design: .rounded))<br>            .foregroundColor(.white)<br>            .fontWeight(.medium)<br>            .monospacedDigit()<br>        } else {<br>          Text(timerInterval: context.state.startedAt...context.state.getFutureDate(),<br>               pauseTime: nil,<br>               countsDown: false,<br>               showsHours: false)<br>            .font(.system(size: 32, weight: .bold, design: .rounded))<br>            .foregroundColor(.white)<br>            .fontWeight(.medium)<br>            .monospacedDigit()<br>        }<br>      }<br>      .padding(.leading, 8)<br>    }<br><br>    DynamicIslandExpandedRegion(.trailing) {<br>      VStack {<br>        Spacer() <br><br>        if context.state.isRunning() {<br>          Button(intent: PauseIntent()) {<br>            ZStack {<br>              Circle()<br>                .fill(Color(hex: &quot;#007bff&quot;))<br>                .frame(width: 44, height: 44)<br>              Image(systemName: &quot;pause.fill&quot;)<br>                .font(.system(size: 18, weight: .bold))<br>                .foregroundColor(.white)<br>            }<br>          }<br>          .buttonStyle(PlainButtonStyle())<br>          .padding(.horizontal, 8)<br>        } else {<br>          HStack(spacing: 8) {<br>            Button(intent: CompleteIntent()) {<br>              ZStack {<br>                Circle()<br>                  .fill(Color(hex: &quot;#28a745&quot;))<br>                  .frame(width: 44, height: 44)<br>                Image(systemName: &quot;checkmark&quot;)<br>                  .font(.system(size: 16, weight: .bold))<br>                  .foregroundColor(.white)<br>              }<br>            }<br>            .buttonStyle(PlainButtonStyle())<br><br>            Button(intent: ResumeIntent()) {<br>              ZStack {<br>                Circle()<br>                  .fill(Color(hex: &quot;#007bff&quot;))<br>                  .frame(width: 44, height: 44)<br>                Image(systemName: &quot;play.fill&quot;)<br>                  .font(.system(size: 18, weight: .bold))<br>                  .foregroundColor(.white)<br>              }<br>            }<br>            .buttonStyle(PlainButtonStyle())<br>          }<br>        }<br>      }<br>      .frame(maxHeight: .infinity) <br>    }<br>  } compactLeading: {<br>    HStack(spacing: 4) {<br>      ActivityIcon(activityIcon: mapJSIconToSFSymbol(context.attributes.activityIcon),<br>                  themeColor: .white,<br>                  size: 16)<br><br>      Text(context.attributes.activityName)<br>        .foregroundColor(.white)<br>        .font(.system(size: 12))<br>        .lineLimit(1)<br>        .truncationMode(.tail)<br>    }<br>  } compactTrailing: {<br>    if !context.state.isRunning() {<br>      Text(context.state.getFormattedElapsedTime())<br>        .foregroundColor(.white)<br>        .monospacedDigit()<br>        .font(.system(size: 12, weight: .medium))<br>    } else {<br>      Text(timerInterval: context.state.startedAt...context.state.getFutureDate(),<br>           pauseTime: nil,<br>           countsDown: false,<br>           showsHours: false)<br>        .foregroundColor(.white)<br>        .monospacedDigit()<br>        .font(.system(size: 12, weight: .medium))<br>    }<br>  } minimal: {<br>    ActivityIcon(activityIcon: mapJSIconToSFSymbol(context.attributes.activityIcon),<br>                themeColor: .white,<br>                size: 12)<br>  }<br>}</pre><ul><li><a href="https://developer.apple.com/design/human-interface-guidelines/live-activities#Expanded-presentation"><strong>Expanded Mode</strong></a>: Shown on long-press, it’s split into .leading and .trailing. The leading side stacks the icon (e.g., a running figure) and name (“Workout”) with a big timer static for paused (getFormattedElapsedTime), ticking for active (Text(timerInterval:)). The trailing side has buttons: a blue pause button when running, or green checkmark (open app) and blue play (resume) when paused. I tweaked fonts and padding to fit the Island’s curves.</li><li><a href="https://developer.apple.com/design/human-interface-guidelines/live-activities#Compact-presentation"><strong>Compact Mode</strong></a>: When space shrinks, compactLeading shows a tiny icon and truncated name, while compactTrailing displays the timer (static or ticking). The .lineLimit(1) keeps the name tidy, and a 12-point font ensures readability.</li><li><a href="https://developer.apple.com/design/human-interface-guidelines/live-activities#Minimal-presentation"><strong>Minimal Mode</strong></a>: Ultra-tight, it’s just a 12-point icon, like a dumbbell, to say “timer’s still here.” Simple but effective.</li></ul><h3>The _shared Folder: Why It’s a Big Deal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*OdZlqw2AXJeTakpTlghLDQ.png" /><figcaption>_shared folder overview</figcaption></figure><p>The _shared folder in <a href="https://github.com/EvanBacon/expo-apple-targets?tab=readme-ov-file#_shared">expo-apple-targets</a> is a top-level directory designed to link essential code to both your main app target and sub-targets, like the Live Activity widget.</p><p>Extensions, such as widgets, operate in separate processes and require specific files to be linked to their target as well as the main app’s. The _shared folder ensures these files are automatically linked to both, eliminating manual configuration. For my timer, I placed the LiveActivityAttributes struct here, guaranteeing the app and widget shared the same timer state (startedAt, pausedAt) without sync issues.</p><h3>Launching the app from Live Activity Widget</h3><p>The CompleteIntent lets users tap a checkmark button on the Live Activity widget to open the app, signaling they’re done with the timer. It’s a simple but crucial interaction for wrapping up a workout.</p><pre>import AppIntents<br>import WidgetKit<br><br>@available(iOS 16.2, *)<br>struct CompleteIntent: AppIntent, LiveActivityIntent {<br>    static var title: LocalizedStringResource = &quot;Complete Exercise&quot;<br>    static var description: IntentDescription = &quot;Opens the app to complete the exercise&quot;<br>    static var openAppWhenRun: Bool = true<br><br>    init() {}<br>    func perform() async throws -&gt; some IntentResult {<br>        NotificationCenter.default.post(name: Notification.Name(&quot;completeActivityFromWidget&quot;), object: nil)<br><br>        return .result()<br>    }<br>}</pre><p>When the user taps the green checkmark, this intent fires, posting a completeActivityFromWidget notification. The native module catches it, triggers the onWidgetCompleteActivity event to JavaScript, and iOS opens the app, thanks to <a href="https://developer.apple.com/documentation/appintents/openurlintent/openappwhenrun">openAppWhenRun</a>: true.</p><h3>Handling User Taps with Intents</h3><p>The PauseIntent is one of the intents that makes the widget interactive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*k2nzvHgwgqj6tFESIFcmbw.png" /><figcaption>Lock Screen Live Activity Intents</figcaption></figure><pre>import AppIntents<br>import WidgetKit<br><br>@available(iOS 16.2, *)<br>struct PauseIntent: AppIntent, LiveActivityIntent {<br>  static var title: LocalizedStringResource = &quot;Pause Timer&quot;<br>  static var description: IntentDescription = &quot;Pauses the current timer.&quot;<br><br>  init() {}<br><br>  func perform() async throws -&gt; some IntentResult {<br>    NotificationCenter.default.post(name: Notification.Name(&quot;pauseTimerFromWidget&quot;), object: nil)<br>    return .result()<br>  }<br>}</pre><p>This intent is triggered when the user taps the pause button on the widget. It’s dead simple but powerful:</p><ul><li>It posts a notification (pauseTimerFromWidget) that the native module catches via setupNotificationObservers.</li><li>The module then runs performPause, updating the Live Activity’s state and notifying JavaScript.</li></ul><p>The beauty here is how intents create a seamless loop: user taps → intent fires → module updates → app stays in sync. expo-apple-targets made setting up intents a breeze by providing a template, but I still had to debug a case where taps didn’t register — turns out, I’d misspelled a notification name. Classic. The <a href="https://docs.expo.dev/modules/overview/">Expo Modules docs</a> helped me understand how to handle events triggered by native actions, which was key to making this work.</p><h3>Events talking to JavaScript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*F5GUBNYqWxbZbLU8-LZ0Ug.png" /></figure><p>The events in the following section are how the native module keeps the React Native app in sync with the Live Activity’s state, using Expo’s event system.</p><h4>onWidgetCompleteActivity</h4><p>This event fires when the user taps the checkmark to complete the activity, triggered by CompleteIntent.</p><pre>@objc func completeIntentHandler(_ notification: Notification) {<br>    guard let currentId = self.currentActivityId, self.startedAt != nil else {<br>        return<br>    }<br><br>    let elapsed = self.calculateElapsedTime()<br><br>    sendEvent(&quot;onWidgetCompleteActivity&quot;, [<br>        &quot;activityId&quot;: currentId,<br>        &quot;elapsedTime&quot;: Int(elapsed)<br>    ])<br>}</pre><p>The completeIntentHandler catches the completeActivityFromWidget notification, calculates the elapsed time, and sends the onWidgetCompleteActivity event to JavaScript with the activity ID and elapsed seconds. JavaScript can then update the app’s UI or log the workout’s completion</p><h4>onLiveActivityUpdate</h4><p>This event fires whenever the timer’s state changes (e.g., pause, resume).</p><pre>private func sendTimerUpdateEvent() {<br>    guard let currentId = self.currentActivityId else { return }<br>    guard self.startedAt != nil else { return }<br><br>    let state = self.pausedAt == nil ? &quot;active&quot; : &quot;paused&quot;<br>    let elapsed = self.calculateElapsedTime()<br><br>    sendEvent(&quot;onLiveActivityUpdate&quot;, [<br>        &quot;state&quot;: state,<br>        &quot;elapsedTime&quot;: Int(elapsed),<br>        &quot;activityId&quot;: currentId<br>    ])<br>}</pre><p>Called after state changes (like in performPause or performResume), it sends the onLiveActivityUpdate event with the current state (“active” or “paused”), elapsed time, and activity ID. JavaScript listens for this to keep the app’s timer UI in sync with the widget.</p><p>Both events create a tight feedback loop between the native module and JavaScript.</p><h3>Why This All Matters</h3><p>This Live Activity isn’t just a timer, it’s a feature that makes my app feel like a native iOS citizen. Here’s why it’s a big deal:</p><ul><li><strong>User Engagement</strong>: Showing a timer on the Lock Screen or Dynamic Island keeps users connected to the app without breaking their flow. It’s perfect for workouts, where every second counts.</li><li><strong>Native Polish</strong>: The widget’s clean design and interactive buttons make the app feel like it belongs on iOS, not like a cross-platform afterthought.</li><li><strong>Performance</strong>: The startedAt/pausedAt approach, powered by Text(timerInterval:), ensures the timer runs smoothly without draining the battery or hitting API limits.</li></ul><p>expo-apple-targets and the <a href="https://docs.expo.dev/modules/module-api/">Expo Modules API</a> were the unsung heroes here, providing a robust framework for bridging JavaScript and Swift. The docs’ emphasis on clean function definitions and event handling kept my code organized and maintainable.</p><h3>Final Thoughts</h3><p>This Live Activity adds a smooth, native feel to the app, showing real-time updates right on the Lock Screen and Dynamic Island. Thanks to expo-apple-targets, the Expo Modules API, and insights from the community (yes, Reddit threads included), bringing it to life was quite straightforward. Live Activities are a powerful way to make apps feel more connected and dynamic.</p><p><strong>Here is the GitHub link for the full source repo 👇🏻</strong><a href="https://github.com/tarikfp/expo-live-activity-timer">https://github.com/tarikfp/expo-live-activity-timer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=626b162f3e8d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-live-activity-timer-in-expo-626b162f3e8d">Building a Live Activity Timer in Expo React Native</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Migrated 182k Users to Supabase]]></title>
            <link>https://levelup.gitconnected.com/how-i-migrated-182k-users-to-supabase-e3c1fb0ed7bf?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c1fb0ed7bf</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 23:53:36 GMT</pubDate>
            <atom:updated>2025-03-30T23:53:36.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Migrated 182,000 Users to Supabase</h3><p><em>From putting it off for months to migrating 182k users — how I finally moved my app to Supabase.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Bqo9a8pTDTjRBa814RSpw.png" /></figure><p>Migrating 182,000 users to a new backend is no small feat — especially when you’re a solo mobile dev juggling a full-time job. But I pulled it off. I transitioned my app, OSM Tactics, from a tangled NestJS + MongoDB setup to Supabase, the hot topic in backend circles right now. In this article, I’ll walk you through the journey: why I chose Supabase, the challenges I faced, and how I pulled off the migration.</p><h4>Why Supabase?</h4><p>When my app’s backend started feeling old, I looked around for something better, and Supabase caught my eye. It’s this open-source thing that’s like Firebase but simpler to jump into. It gives you a PostgreSQL database with an easy API, real-time stuff, and login features all set up. For me, a guy who builds mobile apps, that’s perfect — I don’t want to mess with complicated server junk. You can get a Supabase project running in like five minutes, and the docs are super straightforward, so I didn’t feel lost even though I’m not a backend pro.</p><p>Supabase isn’t just easy, though — it’s getting big. It’s not as huge as Firebase yet, but tons of developers are using it, and the community is growing fast. It’s got everything I need: a database to store stuff, login tools, a place to upload files, and even little functions I can run without a full server. Firebase hides how it works, but Supabase uses PostgreSQL, which is this old, reliable database tons of people trust. That means I can change things how I want and make it bigger later without getting stuck. Plus, there’s a big group of developers online sharing tips, tricks, and fixes on places like GitHub. I knew if I got stuck, I could Google it or ask someone. For a solo coder like me who’s short on time, Supabase felt like the right pick — it’s simple but strong enough to handle my app.</p><h4>The Old Setup Before the Big Switch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*8Dz9gnNI7LqoicSk.gif" /></figure><p>Before I jumped to Supabase, let’s talk about what I was using. My app, <a href="https://apps.apple.com/us/app/osm-tactics/id1632773385">OSM Tactics</a>, is this mobile game for Android and iOS where people plan out tactic strategies — it’s pretty cool if you’re into that. The backend was something I built myself with NestJS, which is a framework for Node.js that I liked because it works with TypeScript and keeps things organized. It talked to MongoDB, a database where I kept all the user info, game data, and other bits. I’d been running this setup for almost four years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPXY2-yvVmlns_ufWV4ZGg.png" /><figcaption>The Latest snapshot of mongodb before migration, Osm Tactics aka “Osm Guide”</figcaption></figure><p>But here’s the problem: I’m just one guy with a full time job, and keeping this backend alive was killing me. At first, NestJS and MongoDB were fine — I could handle them. But as more users joined, it got messy. I had to spend way too much time making sure the server didn’t crash, fixing security holes, and keeping it fast enough. Security was the worst part — I know some Node.js, but I’m a mobile app guy, not a backend expert. It still worked, kind of, but it was like an old car that kept breaking down. I couldn’t keep patching it forever — I needed something new that didn’t make me want to pull my hair out.</p><h4>The Leap: Deciding to Migrate</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*CUFLlvoA2ItnVtEFWJulrg.png" /></figure><p>Deciding to move everything wasn’t quick — it took forever because I kept putting it off. OSM Tactics isn’t some giant app with tons of features, but 182k users is a lot of data to deal with. Going from MongoDB, where data is all loose and free, to Supabase’s PostgreSQL, where everything’s in neat tables, sounded hard. I’d have to redo how the data was set up and make sure I didn’t lose anything important. The old NestJS-MongoDB combo was still running, but I had this bad feeling it’d blow up soon. That worry kept bugging me until I finally said, “Okay, let’s do it.”</p><p>Once I decided, I had to plan it out big time. I sat down and figured out how to turn my MongoDB stuff into Supabase tables — like drawing a map for where everything would go. Step one was getting all my data out of MongoDB safely, so I wrote a little script to dump it into JSON files. Here’s that code — it’s basic but did the job:</p><pre>async function exportCollection(collectionName, outputFileName, query = {}) {<br>  try {<br>    await mongoose.connect(mongoURI);<br><br>    const Model = mongoose.model(<br>      collectionName,<br>      genericSchema,<br>      collectionName.toLowerCase(),<br>    );<br><br>    const documents = await Model.find(query).lean();<br><br>    const outputPath = path.join(__dirname, outputFileName);<br>    fs.writeFileSync(outputPath, JSON.stringify(documents, null, 2));<br><br>    await mongoose.disconnect();<br><br>    return documents;<br>  } catch (error) {<br>    if (mongoose.connection.readyState !== 0) {<br>      await mongoose.disconnect();<br>    }<br>  }<br>}</pre><p>This script hooked up to MongoDB, pulled out all the data, and saved it as JSON files on my computer. It was like a backup — I could mess around without losing everything if I screwed up. I ran it for every collection, checked the files to make sure they looked right, and felt a bit better knowing I had copies. Still, I dragged my feet starting the real work — I’d stare at the screen, sip coffee, and think, “Maybe tomorrow.” It took a big push to stop slacking and actually get into it, but once I did, I was all in.</p><h4>Migrating Users: The Password Puzzle</h4><p>Here’s where it got real hairy: moving 182k users and keeping their passwords working. Users expect to log in with the same email and password after I update the app — that’s just how it should be. But doing it was a nightmare. The cool thing? <a href="https://supabase.com/docs/guides/auth/password-security#how-are-passwords-stored">Supabase uses bcrypt for passwords</a>, same as MongoDB, so I didn’t have to redo them all or make users pick new ones. That would’ve been terrible experience — people hate resetting passwords, and I’d lose a bunch of them.</p><h4>Dealing with Supabase’s Picky Auth Table</h4><p>Supabase has this auth.users table for logins, and it’s super strict. It’s got all these fields you have to fill out just right, or it freaks out — like if you put an empty string instead of null, it breaks. I found some errors other people hit in <a href="https://github.com/supabase/auth/issues/1940">this GitHub thread</a>, and it scared me straight. I had to match it perfectly. Here’s what a user looked like for Supabase (I didn’t use phone stuff, so those are null — change it if you do):</p><pre>const supabaseUser = {<br>  id: uid,<br>  email: user.email,<br>  encrypted_password: user.password || null,<br>  instance_id: &#39;00000000–0000–0000–0000–000000000000&#39;,<br>  aud: &#39;authenticated&#39;,<br>  role: &#39;authenticated&#39;,<br>  email_confirmed_at: user.createdAt<br>    ? new Date(user.createdAt).toISOString()<br>    : new Date().toISOString(),<br>  created_at: user.createdAt<br>    ? new Date(user.createdAt).toISOString()<br>    : new Date().toISOString(),<br>  updated_at: user.updatedAt ? new Date(user.updatedAt).toISOString() : null,<br>  last_sign_in_at: null,<br>  phone: user.phone || null,<br>  phone_confirmed_at: null,<br>  confirmed_at: user.createdAt<br>    ? new Date(user.createdAt).toISOString()<br>    : new Date().toISOString(),<br>  invited_at: null,<br>  confirmation_token: &#39;&#39;,<br>  confirmation_sent_at: null,<br>  recovery_token: &#39;&#39;,<br>  recovery_sent_at: null,<br>  email_change_token_new: &#39;&#39;,<br>  email_change: &#39;&#39;,<br>  email_change_sent_at: null,<br>  email_change_token_current: &#39;&#39;,<br>  email_change_confirm_status: 0,<br>  banned_until: null,<br>  reauthentication_token: &#39;&#39;,<br>  reauthentication_sent_at: null,<br>  is_super_admin: null,<br>  phone_change: &#39;&#39;,<br>  phone_change_token: &#39;&#39;,<br>  phone_change_sent_at: null,<br>  is_sso_user: false,<br>  deleted_at: null,<br>  is_anonymous: false,<br>  raw_user_meta_data: JSON.stringify(rawUserMetaData),<br>  raw_app_meta_data: JSON.stringify(rawAppMetaData),<br>};</pre><p>I had to get every single field right or Supabase wouldn’t take it. To move all my MongoDB users, I wrote a bigger script that grabbed them, turned them into this format, and saved them as a CSV file. Here’s that script — it’s long but shows the whole process:</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const { parse } = require(&#39;json2csv&#39;);<br>const { v4: uuidv4 } = require(&#39;uuid&#39;);<br>const mongoose = require(&#39;mongoose&#39;);<br>const mongoURI = &#39;your-connection-string&#39;;<br><br>// Define a generic schema for flexible document structure<br>const userSchema = new mongoose.Schema({}, { strict: false });<br>async function fetchUsersFromMongoDB() {<br>  try {<br>    console.log(&#39;Connecting to MongoDB…&#39;);<br>    await mongoose.connect(mongoURI);<br>    console.log(&#39;Connected to MongoDB&#39;);<br>    const UserModel = mongoose.model(&#39;Users&#39;, userSchema, &#39;users&#39;);<br>    console.log(&#39;Fetching users from MongoDB…&#39;);<br>    const users = await UserModel.find({}).lean();<br>    console.log(`Found ${users.length} users in MongoDB`);<br>    await mongoose.disconnect();<br>    console.log(&#39;Disconnected from MongoDB&#39;);<br>    return users;<br>  } catch (error) {<br>    console.error(&#39;Error fetching users from MongoDB:&#39;, error);<br>    if (mongoose.connection.readyState !== 0) {<br>      await mongoose.disconnect();<br>    }<br>    throw error;<br>  }<br>}<br><br>async function processUsers() {<br>  console.time(&#39;Total processing time&#39;);<br>  const mongoUsersFilePath = path.join(__dirname, &#39;mongo_users.json&#39;);<br>  try {<br>    // Step 1: Fetch users from MongoDB<br>    const users = await fetchUsersFromMongoDB();<br>    // Step 2: Write users to a fresh JSON file<br>    fs.writeFileSync(mongoUsersFilePath, JSON.stringify(users, null, 2));<br>    console.log(`Fresh users data written to: ${mongoUsersFilePath}`);<br>    // Step 3: Read the fresh users file<br>    const usersData = JSON.parse(fs.readFileSync(mongoUsersFilePath, &#39;utf8&#39;));<br>    console.log(`Read ${usersData.length} users from fresh file`);<br>    // Step 4: Filter users to include only those with an email or at least one provider<br>    const filteredUsers = usersData.filter((user) =&gt; {<br>      return user.email || user.googleId || user.appleId;<br>    });<br>    console.log(`Filtered users: ${filteredUsers.length}`);<br>    // Create a Set to track used IDs and ensure uniqueness<br>    const usedIds = new Set();<br>    const usedEmails = new Set();<br>    const duplicateEmails = [];<br>    // Step 5: Transform the data to match Supabase Auth users structure<br>    const transformedUsers = [];<br>    filteredUsers.forEach((user) =&gt; {<br>      if (!user.email) {<br>        console.log(&#39;Skipping user without email:&#39;, user._id);<br>        return;<br>      }<br>      // Check for duplicate email<br>      const lowerEmail = user.email.toLowerCase();<br>      if (usedEmails.has(lowerEmail)) {<br>        duplicateEmails.push({<br>          email: user.email,<br>          id: user._id,<br>          googleId: user.googleId,<br>          appleId: user.appleId,<br>        });<br>        console.warn(`Duplicate email detected and skipped: ${user.email}`);<br>        return;<br>      }<br>      // Mark this email as used<br>      usedEmails.add(lowerEmail);<br>      let uid = uuidv4();<br>      while (usedIds.has(uid)) {<br>        console.warn(&#39;Duplicate ID detected:&#39;, uid);<br>        uid = uuidv4();<br>      }<br>      usedIds.add(uid);<br>      const rawUserMetaData = {<br>        sub: uid,<br>        email: user.email,<br>        email_verified: true,<br>        phone_verified: false,<br>      };<br>      const providers = [];<br>      // Check for Google ID<br>      if (user.googleId) {<br>        providers.push(&#39;google&#39;);<br>        rawUserMetaData.iss = &#39;https://accounts.google.com&#39;;<br>        rawUserMetaData.sub = user.googleId;<br>        rawUserMetaData.provider_id = user.googleId;<br>      }<br>      // Check for Apple ID<br>      if (user.appleId) {<br>        providers.push(&#39;apple&#39;); // Only override iss and sub if Google wasn&#39;t already set<br>        if (!user.googleId) {<br>          rawUserMetaData.iss = &#39;https://appleid.apple.com&#39;;<br>          rawUserMetaData.sub = user.appleId;<br>          rawUserMetaData.provider_id = user.appleId;<br>        }<br>      }<br>      // If no external providers, use email<br>      if (providers.length === 0) {<br>        providers.push(&#39;email&#39;);<br>      }<br>      // Set the raw app metadata<br>      const rawAppMetaData = {<br>        provider: providers[0], // Primary provider is the first one<br>        providers: providers, // All providers in an array<br>      };<br>      transformedUsers.push({<br>        id: uid,<br>        email: user.email || null,<br>        encrypted_password: user.password,<br>        instance_id: &#39;00000000–0000–0000–0000–000000000000&#39;,<br>        aud: &#39;authenticated&#39;,<br>        role: &#39;authenticated&#39;,<br>        invited_at: null,<br>        confirmation_token: &#39;&#39;,<br>        confirmation_sent_at: null,<br>        recovery_token: &#39;&#39;,<br>        recovery_sent_at: null,<br>        email_change_token_new: &#39;&#39;,<br>        email_change: &#39;&#39;,<br>        email_change_sent_at: null,<br>        last_sign_in_at: new Date().toISOString(),<br>        is_super_admin: null,<br>        phone: &#39;&#39;,<br>        phone_confirmed_at: null,<br>        phone_change: &#39;&#39;,<br>        phone_change_token: &#39;&#39;,<br>        phone_change_sent_at: null,<br>        confirmed_at: new Date().toISOString(),<br>        email_change_token_current: &#39;&#39;,<br>        email_change_confirm_status: 0,<br>        banned_until: null,<br>        reauthentication_token: &#39;&#39;,<br>        reauthentication_sent_at: null,<br>        is_sso_user: false,<br>        deleted_at: null,<br>        is_anonymous: false,<br>        created_at: user.createdAt<br>          ? new Date(user.createdAt).toISOString()<br>          : new Date().toISOString(),<br>        updated_at: null,<br>        email_confirmed_at: user.createdAt<br>          ? new Date(user.createdAt).toISOString()<br>          : new Date().toISOString(),<br>        phone: user.phone || null,<br>        phone_confirmed_at: null,<br>        raw_user_meta_data: rawUserMetaData,<br>        raw_app_meta_data: rawAppMetaData,<br>      });<br>    });<br>    // Step 6: Convert the transformed data to CSV<br>    const csvFields = [<br>      &#39;id&#39;,<br>      &#39;email&#39;,<br>      &#39;encrypted_password&#39;,<br>      &#39;instance_id&#39;,<br>      &#39;aud&#39;,<br>      &#39;role&#39;,<br>      &#39;email_confirmed_at&#39;,<br>      &#39;invited_at&#39;,<br>      &#39;confirmation_token&#39;,<br>      &#39;confirmation_sent_at&#39;,<br>      &#39;recovery_token&#39;,<br>      &#39;recovery_sent_at&#39;,<br>      &#39;email_change_token_new&#39;,<br>      &#39;email_change&#39;,<br>      &#39;email_change_sent_at&#39;,<br>      &#39;last_sign_in_at&#39;,<br>      &#39;raw_app_meta_data&#39;,<br>      &#39;raw_user_meta_data&#39;,<br>      &#39;is_super_admin&#39;,<br>      &#39;created_at&#39;,<br>      &#39;updated_at&#39;,<br>      &#39;phone&#39;,<br>      &#39;phone_confirmed_at&#39;,<br>      &#39;phone_change&#39;,<br>      &#39;phone_change_token&#39;,<br>      &#39;phone_change_sent_at&#39;,<br>      &#39;confirmed_at&#39;,<br>      &#39;email_change_token_current&#39;,<br>      &#39;email_change_confirm_status&#39;,<br>      &#39;banned_until&#39;,<br>      &#39;reauthentication_token&#39;,<br>      &#39;reauthentication_sent_at&#39;,<br>      &#39;is_sso_user&#39;,<br>      &#39;deleted_at&#39;,<br>      &#39;is_anonymous&#39;,<br>    ];<br>    // Write duplicate emails to a file for reference<br>    if (duplicateEmails.length &gt; 0) {<br>      fs.writeFileSync(<br>        path.join(__dirname, &#39;duplicate_emails.json&#39;),<br>        JSON.stringify(duplicateEmails, null, 2),<br>      );<br>      console.log(&#39;Duplicate emails written to duplicate_emails.json&#39;);<br>    }<br>    const csv = parse(transformedUsers, { fields: csvFields });<br>    // Step 7: Write the CSV to a file<br>    const csvFilePath = path.join(__dirname, &#39;supabase_users.csv&#39;);<br>    fs.writeFileSync(csvFilePath, csv);<br>    console.log(&#39;CSV file has been generated:&#39;, csvFilePath);<br>    // Step 8: Delete the temporary fresh users file<br>    if (fs.existsSync(mongoUsersFilePath)) {<br>      fs.unlinkSync(mongoUsersFilePath);<br>      console.log(`Temporary file deleted: ${mongoUsersFilePath}`);<br>    }<br>    console.timeEnd(&#39;Total processing time&#39;);<br>  } catch (error) {<br>    console.error(&#39;Error processing users:&#39;, error);<br>  } finally {<br>    if (fs.existsSync(mongoUsersFilePath)) {<br>      try {<br>        fs.unlinkSync(mongoUsersFilePath);<br>        console.log(`Temporary file deleted: ${mongoUsersFilePath}`);<br>      } catch (deleteError) {<br>        console.error(`Error deleting temporary file: ${deleteError.message}`);<br>      }<br>    }<br>  }<br>}<br></pre><p>After I had that CSV, I made a fake table in Supabase that looked like auth.users. The real table’s setup is this long SQL thing you can see in Supabase’s editor under schema auth &gt; users &gt; Definition:</p><pre>create table auth.users (<br>  instance_id uuid null,<br>  id uuid not null,<br>  aud character varying(255) null,<br>  role character varying(255) null,<br>  email character varying(255) null,<br>  encrypted_password character varying(255) null,<br>  email_confirmed_at timestamp with time zone null,<br>  invited_at timestamp with time zone null,<br>  confirmation_token character varying(255) null,<br>  confirmation_sent_at timestamp with time zone null,<br>  recovery_token character varying(255) null,<br>  recovery_sent_at timestamp with time zone null,<br>  email_change_token_new character varying(255) null,<br>  email_change character varying(255) null,<br>  email_change_sent_at timestamp with time zone null,<br>  last_sign_in_at timestamp with time zone null,<br>  raw_app_meta_data jsonb null,<br>  raw_user_meta_data jsonb null,<br>  is_super_admin boolean null,<br>  created_at timestamp with time zone null,<br>  updated_at timestamp with time zone null,<br>  phone text null default null::character varying,<br>  phone_confirmed_at timestamp with time zone null,<br>  phone_change text null default &#39;&#39;::character varying,<br>  phone_change_token character varying(255) null default &#39;&#39;::character varying,<br>  phone_change_sent_at timestamp with time zone null,<br>  confirmed_at timestamp with time zone GENERATED ALWAYS as (LEAST(email_confirmed_at, phone_confirmed_at)) STORED null,<br>  email_change_token_current character varying(255) null default &#39;&#39;::character varying,<br>  email_change_confirm_status smallint null default 0,<br>  banned_until timestamp with time zone null,<br>  reauthentication_token character varying(255) null default &#39;&#39;::character varying,<br>  reauthentication_sent_at timestamp with time zone null,<br>  is_sso_user boolean not null default false,<br>  deleted_at timestamp with time zone null,<br>  is_anonymous boolean not null default false,<br>  constraint users_pkey primary key (id),<br>  constraint unique_email unique (email),<br>  constraint users_phone_key unique (phone),<br>  constraint users_email_change_confirm_status_check check (<br>    (<br>      (email_change_confirm_status &gt;= 0)<br>      and (email_change_confirm_status &lt;= 2)<br>    )<br>  )<br>) TABLESPACE pg_default;<br><br>create unique INDEX IF not exists confirmation_token_idx on auth.users using btree (confirmation_token) TABLESPACE pg_default<br>where<br>  ((confirmation_token)::text !~ &#39;^[0-9 ]*$&#39;::text);<br><br>create unique INDEX IF not exists email_change_token_current_idx on auth.users using btree (email_change_token_current) TABLESPACE pg_default<br>where<br>  (<br>    (email_change_token_current)::text !~ &#39;^[0-9 ]*$&#39;::text<br>  );<br><br>create unique INDEX IF not exists email_change_token_new_idx on auth.users using btree (email_change_token_new) TABLESPACE pg_default<br>where<br>  (<br>    (email_change_token_new)::text !~ &#39;^[0-9 ]*$&#39;::text<br>  );<br><br>create unique INDEX IF not exists reauthentication_token_idx on auth.users using btree (reauthentication_token) TABLESPACE pg_default<br>where<br>  (<br>    (reauthentication_token)::text !~ &#39;^[0-9 ]*$&#39;::text<br>  );<br><br>create unique INDEX IF not exists recovery_token_idx on auth.users using btree (recovery_token) TABLESPACE pg_default<br>where<br>  ((recovery_token)::text !~ &#39;^[0-9 ]*$&#39;::text);<br><br>create unique INDEX IF not exists users_email_partial_key on auth.users using btree (email) TABLESPACE pg_default<br>where<br>  (is_sso_user = false);<br><br>create index IF not exists users_instance_id_email_idx on auth.users using btree (instance_id, lower((email)::text)) TABLESPACE pg_default;<br><br>create index IF not exists users_instance_id_idx on auth.users using btree (instance_id) TABLESPACE pg_default;<br><br>create index IF not exists users_is_anonymous_idx on auth.users using btree (is_anonymous) TABLESPACE pg_default;</pre><p>I copied that setup for my temp table, uploaded the CSV into it, and then used this script to move users into the real auth.users table a thousand at a time:</p><pre>DO $$<br>DECLARE<br>    batch_size INT := 1000;  -- Adjust batch size as needed<br>    records_inserted INT;<br>BEGIN<br>    LOOP<br>        INSERT INTO auth.users (<br>            id,<br>            email,<br>            encrypted_password,<br>            instance_id,<br>            aud,<br>            role,<br>            email_confirmed_at,<br>            invited_at,<br>            confirmation_token,<br>            confirmation_sent_at,<br>            recovery_token,<br>            recovery_sent_at,<br>            email_change_token_new,<br>            email_change,<br>            email_change_sent_at,<br>            last_sign_in_at,<br>            raw_app_meta_data,<br>            raw_user_meta_data,<br>            is_super_admin,<br>            created_at,<br>            updated_at,<br>            phone,<br>            phone_confirmed_at,<br>            phone_change,<br>            phone_change_token,<br>            phone_change_sent_at,<br>            email_change_token_current,<br>            email_change_confirm_status,<br>            banned_until,<br>            reauthentication_token,<br>            reauthentication_sent_at,<br>            is_sso_user,<br>            deleted_at,<br>            is_anonymous<br>        )<br>        SELECT<br>            id,<br>            email,<br>            encrypted_password,<br>            COALESCE(instance_id, &#39;00000000-0000-0000-0000-000000000000&#39;),<br>            COALESCE(aud, &#39;authenticated&#39;),<br>            COALESCE(NULLIF(role, &#39;&#39;), &#39;authenticated&#39;),<br>            COALESCE(email_confirmed_at, NOW()),<br>            COALESCE(invited_at, NULL),<br>            COALESCE(confirmation_token, &#39;&#39;),<br>            COALESCE(confirmation_sent_at, NULL),<br>            COALESCE(recovery_token, &#39;&#39;),<br>            COALESCE(recovery_sent_at, NULL),<br>            COALESCE(email_change_token_new, &#39;&#39;),<br>            COALESCE(email_change, &#39;&#39;),<br>            COALESCE(email_change_sent_at, NULL),<br>            COALESCE(last_sign_in_at, NOW()),<br>            raw_app_meta_data,  -- Use value from test_users table<br>            raw_user_meta_data, -- Use value from test_users table<br>            COALESCE(is_super_admin, NULL),<br>            COALESCE(created_at, NOW()),<br>            COALESCE(updated_at, NOW()),<br>            COALESCE(phone, NULL),<br>            COALESCE(phone_confirmed_at, NULL),<br>            COALESCE(phone_change, &#39;&#39;),<br>            COALESCE(phone_change_token, &#39;&#39;),<br>            COALESCE(phone_change_sent_at, NULL),<br>            COALESCE(email_change_token_current, &#39;&#39;),<br>            COALESCE(email_change_confirm_status, 0),<br>            COALESCE(banned_until, NULL),<br>            COALESCE(reauthentication_token, &#39;&#39;),<br>            COALESCE(reauthentication_sent_at, NULL),<br>            COALESCE(is_sso_user, false),<br>            COALESCE(deleted_at, NULL),<br>            COALESCE(is_anonymous, false)<br>        FROM public.test_users<br>        LIMIT batch_size<br>        ON CONFLICT (email) DO NOTHING;  -- Ignore duplicates<br><br>        GET DIAGNOSTICS records_inserted = ROW_COUNT;<br><br>        -- Exit the loop if no more records are inserted<br>        IF records_inserted = 0 THEN<br>            EXIT;<br>        END IF;<br>    END LOOP;<br>END $$;</pre><p>This way, I could see every step — exporting, changing, loading. It took longer than some fancy tool might’ve, but I liked knowing exactly what was happening. I’d check the temp table after loading the CSV, spot-check a few rows, and then watch the batch script run to make sure it didn’t choke.</p><h4>No Room for Custom Fields</h4><p>Supabase’s auth.users table doesn’t let you add your own fields, which threw me off. In MongoDB, I’d just stick a username field in there, no big deal. But Supabase says no — you’re stuck with what it gives you. I thought about shoving extra stuff into raw_user_meta_data, which is like a JSON bag, but that’s messy for searching later. Instead, I made a new profiles table that connects to auth.users with the user ID. It holds things like username and locale, keeping it all tidy.</p><p>Also see this discussion which might be helpful: <a href="https://github.com/orgs/supabase/discussions/3491">https://github.com/orgs/supabase/discussions/3491</a></p><p>Setting this up meant more work — I had to pull those extra fields from MongoDB, match them to the right users, and load them into the new table. I wrote another script to grab that data, turned it into a CSV, and uploaded it to Supabase after the auth stuff was done. It’s a better setup now because I can add more fields later without breaking anything, but it made the migration take longer since I had two tables to deal with instead of one.</p><h4>Migration of Google/Apple Sign-Ins</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ojwVN2SEuLBx9Ybn.jpeg" /></figure><p>Google and Apple logins were a pain too. In MongoDB, I had googleId and appleId fields, and some users had both tied to one email. Supabase handles these with special fields in raw_user_meta_data like iss, sub, and provider_id.</p><p>Here’s how I set it up:</p><pre>const uid = uuidv4();<br>const providers = [];<br>// Build raw user metadata<br>const rawUserMetaData = {<br>  sub: uid,<br>  email: user.email,<br>  email_verified: true,<br>  phone_verified: false,<br>};<br>// Check for Google ID<br>if (user.googleId) {<br>  providers.push(&#39;google&#39;);<br>  rawUserMetaData.iss = &#39;https://accounts.google.com&#39;;<br>  rawUserMetaData.sub = user.googleId;<br>  rawUserMetaData.provider_id = user.googleId;<br>}<br>// Check for Apple ID<br>if (user.appleId) {<br>  providers.push(&#39;apple&#39;);<br>  if (!user.googleId) {<br>    rawUserMetaData.iss = &#39;https://appleid.apple.com&#39;;<br>    rawUserMetaData.sub = user.appleId;<br>    rawUserMetaData.provider_id = user.appleId;<br>  }<br>}<br>// If no external providers, use email<br>if (providers.length === 0) {<br>  providers.push(&#39;email&#39;);<br>}</pre><p>In the app, I updated the sign-in flows to use Supabase’s APIs. For Apple:</p><pre>import * as AppleAuthentication from &#39;expo-apple-authentication&#39;;<br>import { supabase } from &#39;your-supabase-client&#39;;<br><br>const credential = await AppleAuthentication.signInAsync({<br>  requestedScopes: [<br>    AppleAuthentication.AppleAuthenticationScope.FULL_NAME,<br>    AppleAuthentication.AppleAuthenticationScope.EMAIL,<br>  ],<br>});<br>if (credential.identityToken) {<br>  const { data, error } = await supabase.auth.signInWithIdToken({<br>    provider: &#39;apple&#39;,<br>    token: credential.identityToken,<br>  });<br>}</pre><p>And for Google:</p><pre>import { GoogleSignin } from &#39;@react-native-google-signin/google-signin&#39;;<br>import { supabase } from &#39;your-supabase-client&#39;;<br><br>const googleUser = await GoogleSignin.signIn();<br><br>if (googleUser.idToken) {<br>  const { data, error } = await supabase.auth.signInWithIdToken({<br>    provider: &#39;google&#39;,<br>    token: googleUser.idToken,<br>  });<br>}</pre><p>It worked, but figuring out users with both Google and Apple was tricky — I had to pick one as the main ID and list the other as extra. I tested it a bunch in the app to make sure nobody got locked out.</p><blockquote><strong>Caveat: CSV Export Potential Issues in Supabase</strong></blockquote><blockquote>As of today (29/03/2025), exporting table data as CSV might be <a href="https://github.com/supabase/supabase/issues/27102">unreliable</a> — so keep that in mind when comparing data between Supabase and your original source.</blockquote><h4>Generating TypeScript Types</h4><p>Supabase has this awesome trick where it makes TypeScript types for you. <a href="https://supabase.com/docs/guides/api/rest/generating-types#generating-types-using-supabase-cli">You run one command</a>, and it spits out files that tell your code exactly what your database looks like. For my React Native and Expo app, that was huge — I didn’t have to guess what data I’d get or write my own types. It cut down on bugs big time because TypeScript yelled at me if I messed up. Before, I’d spend hours fixing dumb mistakes; now, it’s way faster.</p><p>I ran the command after setting up my tables, got the types file, and plugged it into my app. Suddenly, stuff like user.email or profile.username just worked — no more wondering if I spelled it right. It’s a small thing, but it made coding the app feel less like a guessing game and more like a win.</p><h4>Making Database Functions Do the Work</h4><p>Supabase lets you write little SQL functions that run in the database, which is super handy. Instead of doing a bunch of app-side code to change stuff, I let the database handle it.</p><p>Here’s one I made to add credits to a user’s profile:</p><pre><br>declare<br>  current_credits int;<br>  new_credits int;<br>begin<br>  -- Get current credits from user_profiles table<br>  select assistant_credits<br>  into current_credits <br>  from public.user_profiles <br>  where public.user_profiles.user_id = increase_assistant_credits.user_id;<br><br>  if current_credits is null then<br>    current_credits := 0;<br>  end if;<br><br>  new_credits := current_credits + credits_to_add;<br>  <br>  -- Update assistant_credits in user_profiles table<br>  update public.user_profiles <br>  set assistant_credits = new_credits<br>  where public.user_profiles.user_id = increase_assistant_credits.user_id;<br><br>  return new_credits;<br>end;</pre><p>This grabs the user’s credits, adds some, and saves it back — all in one go. Without it, I’d have to fetch the credits, add them in the app, and send them back, which is more code and more chances to mess up. I wrote a few of these for other tasks too, and it made my app feel snappier since the database did the heavy lifting.</p><h4>The Backend Caveat</h4><p>Here’s a twist: Supabase didn’t get rid of my backend completely. To use some admin login stuff, you need this <a href="https://supabase.com/docs/guides/api/api-keys#the-servicerole-key">service_role key</a>, but you can’t put it in the app — it’s not safe. So, I kept a small NestJS server to handle those secret jobs. It’s not as big as before, but it’s there to keep things locked down. Supabase does most of the work, so it’s still way easier than my old setup.</p><h4>Conclusion: Worth the Struggle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*rugop3f6Ns9U4Ayl.jpg" /></figure><p>Migrating 182,000 users to Supabase wasn’t just a technical challenge — it was a mental one too. Between procrastination, late nights, and plenty of second-guessing, there were moments I genuinely thought I might break everything. It was a slow grind, full of stress and hesitation. But leaving behind the brittle NestJS + MongoDB setup and moving to something cleaner and more maintainable was absolutely worth it.</p><p>Supabase gave me the simplicity, flexibility, and community support I needed as a solo dev juggling a full-time job. If you’re thinking about migrating your own app’s backend, just know it’s totally doable. It won’t be quick or painless — but with a bit of planning (and probably a few long nights), you’ll come out on the other side with a setup you can actually trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c1fb0ed7bf" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-migrated-182k-users-to-supabase-e3c1fb0ed7bf">How I Migrated 182k Users to Supabase</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple Wallet Animation In React Native]]></title>
            <link>https://levelup.gitconnected.com/apple-wallet-animation-in-react-native-2faaf4dd10a4?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2faaf4dd10a4</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 19:41:19 GMT</pubDate>
            <atom:updated>2024-04-07T19:41:19.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDYjA-wGrZ4mdEEKoGHXfw.jpeg" /></figure><p>Animations are a fundamental enhancement tool in mobile apps. This article covers implementing Apple Wallet animations on the iOS platform using React Native.</p><p>We’ll skip diving deep into app setup, file structure, and component initialization, focusing instead on implementing animation with pre-prepared components. I’ll provide the complete component code snippet while focusing on the animation aspect.</p><p>You can expect me to share the final source code via a GitHub link at the end of this article.</p><h4>The Latest Picture Before We Break Down Things</h4><p>For those eager to see the end result without reading through the entire article, here’s a glimpse of the final app. We’ll dissect each part in detail below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Z57FxjAoQrBXYEhXRedKEw.gif" /><figcaption>React Native Apple Wallet Animation Demo</figcaption></figure><h4>App structure</h4><p>The app is designed to be straightforward, primarily to showcase Apple Wallet view animations. It features two screens: the Card List, displaying Apple Wallet-like cards, and the Card Detail, showing the details of a selected card.</p><p>Let’s first start with our Card List screen:</p><h4>Card List Screen</h4><p>In the Card List component, we need four mixed variables. I refer to them as variables, though they are a mix of useState, useRef, useSharedValue, etc.</p><p>Here they are:</p><pre>import { useRef, useState } from &quot;react&quot;;<br>import { useSharedValue } from &quot;react-native-reanimated&quot;;<br><br>const flatListRef = useRef&lt;FlatList | null&gt;(null);<br>const [cardsData, setCardsData] = useState&lt;Array&lt;CardData&gt;&gt;(data);<br>const [shouldDisplayAsStack, setShouldDisplayAsStack] = useState(true);<br>const scrollY = useSharedValue(0);</pre><ul><li><strong>flatListRef</strong>: This will be attached to the FlatList component we use in our CardList component to display cards vertically. We’ll use flatListRef when performing the scrollToIndex action to scroll to the top on toggling card stacks.</li><li><strong>cardsData: </strong>A React state to store our hardcoded/static card data. There’s no need to fetch card data from an external source for this example.</li><li><strong>shouldDisplayAsStack: </strong>Indicates whether our cards should be displayed stacked in the list.</li><li><strong>scrollY</strong>: A shared value used to track the user’s scroll position vertically. This variable is primarily used when performing card animations.</li></ul><h4>Utilizing Animated.FlatList’s Scroll Handler</h4><p>We created scrollY using a shared variable to track the scroll position. Now, it&#39;s time to use this variable with Animated.FlatList:</p><pre>import { useAnimatedScrollHandler } from &quot;react-native-reanimated&quot;;<br><br>const scrollHandler = useAnimatedScrollHandler((event) =&gt; {<br>   scrollY.value = event.contentOffset.y;<br>});<br><br>&lt;Animated.FlatList onScroll={scrollHandler} /&gt;</pre><p>Here, we import the useAnimatedScrollHandler hook to create a scrollHandler as an onScroll prop of Animated.FlatList. This allows us to subscribe to the scrollY value in real-time in the UI thread, thanks to shared values. Updating the value in the UI thread enables us to create seamless animations without burdening the JS stack, a significant advantage of using react-native-reanimated.</p><h4>Handling the onPress action of the Card component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*KCawwbVS6zqe7TdWC9TRDA.gif" /></figure><p>Pressing a card component that is not the last item will push the card to the last position in the list. Let’s see this action in the code:</p><pre>  import { LayoutAnimation } from &quot;react-native&quot;;<br><br>  const onCardPress = useCallback(<br>    (item: CardData, index: number) =&gt; () =&gt; {<br>      const isLastItem = cardsData.length - 1 === index;<br><br>      // pressed card is the last item, navigate to the card detail<br>      if (isLastItem) {<br>        navigation.navigate(&quot;CardDetail&quot;, {<br>          item,<br>        });<br>        return;<br>      }<br><br>      LayoutAnimation.configureNext(<br>        LayoutAnimation.Presets.easeInEaseOut<br>      );<br><br>      setCardsData((prev) =&gt; [<br>        ...prev.filter((prevData) =&gt; prevData.id !== item.id),<br>        item,<br>      ]);<br>    },<br>    []<br>  );</pre><p>To push the selected card item to the end of the list, we first determine whether the pressed card item is the last. If it is the last item, we navigate to the Card Detail screen. We use setCardsData to reorder card items, ensuring the selected card item is pushed to the end of the list. We also utilize <a href="https://reactnative.dev/docs/layoutanimation">LayoutAnimation</a> from react-native to create this swap animation seamlessly.</p><h4>Pressing the Last Card Item in the List</h4><p>We’ve covered the action for pressing a card item that is not the last item. Now, let’s handle pressing the last card item in the list. We want to navigate to the Card Detail screen and have the last item transition smoothly. In more technical terms, we want the last card list item to perform shared element transition.</p><p>Let&#39;s see it visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*yK458fGBPOL-1eaOaT075w.gif" /><figcaption>Shared element transition</figcaption></figure><p>As can seen above, pressing the last item of the list performs shared element transition. Now let&#39;s come to the topic of how we would implement it. We will be utilizing the library called <a href="https://github.com/IjzerenHein/react-navigation-shared-element">react-navigation-shared-element</a>.</p><h4>Utilizing <a href="https://github.com/IjzerenHein/react-navigation-shared-element">react-navigation-shared-element</a></h4><p>To achieve the smooth and visually engaging transitions discussed, creating a navigation stack that supports these transitions is crucial. The react-navigation-shared-element library provides the necessary tools to bring these animations to life in a React Native application.</p><p>Here are the steps to achieve shared element transitions:</p><ul><li>Building Navigation Stack using react-navigation-shared-element</li><li>Use the SharedElement component as a wrapper.</li><li>Provide a unique id prop for each card in the list using SharedElement</li></ul><h4>Building the Shared Element Navigation Stack</h4><p>The engagement of these transitions depends on setting up our navigation stack with the react-navigation-shared-element library. This specialized stack navigator is aware of shared elements between screens, allowing for animations that transition elements smoothly from one screen to another.</p><p>Here’s how we set it up:</p><pre>import { NavigationContainer } from &quot;@react-navigation/native&quot;;<br>import { StackScreenProps } from &quot;@react-navigation/stack&quot;;<br>import { Platform } from &quot;react-native&quot;;<br>import { createSharedElementStackNavigator } from &quot;react-navigation-shared-element&quot;;<br>import { CardData } from &quot;./data&quot;;<br>import { CardDetail } from &quot;./screens/card-detail&quot;;<br>import CardList from &quot;./screens/card-list&quot;;<br><br>type CardStackParamList = {<br>  CardList: undefined;<br>  CardDetail: { item: CardData };<br>};<br><br>export type CardStackScreenProps&lt;<br>  RouteName extends keyof CardStackParamList<br>&gt; = StackScreenProps&lt;CardStackParamList, RouteName&gt;;<br><br>const SharedElementStack =<br>  createSharedElementStackNavigator&lt;CardStackParamList&gt;();<br><br>export default function CardsStack() {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      &lt;SharedElementStack.Navigator initialRouteName=&quot;CardList&quot;&gt;<br>        &lt;SharedElementStack.Screen<br>          name=&quot;CardList&quot;<br>          component={CardList}<br>          options={{<br>            gestureEnabled: false,<br>            headerLeftContainerStyle: {<br>              paddingLeft: 12,<br>            },<br>            headerRightContainerStyle: {<br>              paddingRight: 12,<br>            },<br>            headerTitle: &quot;My Wallet&quot;,<br>          }}<br>        /&gt;<br>        &lt;SharedElementStack.Screen<br>          name=&quot;CardDetail&quot;<br>          component={CardDetail}<br>          options={{<br>            headerTitle: &quot;Card Detail&quot;,<br>            cardStyle: {<br>              backgroundColor: &quot;#EFEFF4&quot;,<br>            },<br>          }}<br>          sharedElements={(route, otherRoute, _showing) =&gt; {<br>            const { item } = route.params;<br><br>            // we want to execute shared element transition only in iOS<br>            // and when transitioning from card list screen<br>            if (<br>              otherRoute.name === &quot;CardList&quot; &amp;&amp;<br>              Platform.OS === &quot;ios&quot;<br>            ) {<br>              return [<br>                {<br>                  id: item.id,<br>                },<br>              ];<br>            }<br>          }}<br>        /&gt;<br>      &lt;/SharedElementStack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>  );<br>}</pre><p>In our setup, the shared element transition is defined within the CardDetail screen configuration, specifically through the sharedElements prop. This approach allows us to specify which elements should animate during the transition between screens, providing a more connected and fluid user experience.</p><pre>sharedElements={(route, otherRoute, _showing) =&gt; {<br>  const { item } = route.params;<br>  if (otherRoute.name === &quot;CardList&quot; &amp;&amp; Platform.OS === &quot;ios&quot;) {<br>    return [{<br>      id: item.id<br>    }];<br>  }<br>}}</pre><p>Let’s delve into what is discussed above:</p><p>Condition Check: The function checks whether the transition is from the CardList screen and is occurring on an iOS device. This selective application ensures that the shared element transition is used in contexts where it provides the most value, aligning with the platform-specific design considerations and enhancing the overall user experience on iOS.</p><p>Element Selection: The transition involves elements identified by a unique id, which is passed through the navigation parameters. This id links the element on the initial screen with its counterpart on the subsequent screen, enabling the library to animate the transition of this element seamlessly.</p><h4>Using SharedElement component</h4><p>The SharedElement component from the react-navigation-shared-element library is like a magic wand for our animations. Wrapping our Card component with it allows us to specify which elements should animate together when moving between screens. In simpler terms, it tells our app, &quot;Hey, see this element? Keep your eyes on it as we move to the next screen, and make sure it transitions smoothly.&quot; This is crucial for maintaining visual continuity and making the app feel more fluid.</p><p>Imagine tapping on a card in a list to view its details; without the SharedElement wrapper, the new screen would just pop up, and the connection between the action and the result might feel a bit disjointed. With SharedElement, however, the card seamlessly expands into the details view, making the interaction feel more natural and connected.</p><h4>The Role of SharedElement in Transition</h4><p>The SharedElement wrapper takes the id prop to identify the card across screens. When you navigate from one screen to another, the library uses this ID to find the corresponding element on both screens and animates the transition between their states. This means the card in the list and the card or image in the detail view are linked, allowing for a seamless visual transition that feels like you&#39;re expanding the same element rather than jumping between screens.</p><h4>SharedElement in Card Component</h4><p>Let’s examine the Card component used in the CardList screen to represent our card items:</p><pre>import React, { memo } from &quot;react&quot;;<br>import { ImageSourcePropType } from &quot;react-native&quot;;<br>import { BaseButton } from &quot;react-native-gesture-handler&quot;;<br>import Animated, {<br>  Extrapolation,<br>  SharedValue,<br>  interpolate,<br>  useAnimatedStyle,<br>  withSpring,<br>} from &quot;react-native-reanimated&quot;;<br>import { SharedElement } from &quot;react-navigation-shared-element&quot;;<br>import {<br>  CARD_BORDER_RADIUS,<br>  CARD_HEIGHT,<br>  CARD_WIDTH,<br>  mobileKeyCardTranslateYOutput,<br>} from &quot;./constants&quot;;<br><br>type Props = {<br>  onPress?: () =&gt; void;<br>  index: number;<br>  scrollY: SharedValue&lt;number&gt;;<br>  shouldDisplayAsStack?: boolean;<br>  sharedElementId: string;<br>  imageSource: ImageSourcePropType;<br>};<br><br>const CardInner: React.FC&lt;Props&gt; = ({<br>  shouldDisplayAsStack = false,<br>  sharedElementId,<br>  onPress,<br>  scrollY,<br>  imageSource,<br>  index: i,<br>}) =&gt; {<br>  const animatedStyle = useAnimatedStyle(() =&gt; {<br>    const animatedTop = interpolate(<br>      scrollY.value,<br>      [-50, 0, 50, 300],<br>      mobileKeyCardTranslateYOutput,<br>      Extrapolation.CLAMP<br>    );<br><br>    return {<br>      height: CARD_HEIGHT,<br>      width: CARD_WIDTH,<br>      borderRadius: CARD_BORDER_RADIUS,<br>      transform: [<br>        {<br>          translateY: withSpring(<br>            shouldDisplayAsStack ? i * animatedTop : 0,<br>            {<br>              damping: 15,<br>              mass: 0.8,<br>              stiffness: 100,<br>              overshootClamping: false,<br>              restDisplacementThreshold: 0.1,<br>              restSpeedThreshold: 0.1,<br>            }<br>          ),<br>        },<br>      ],<br>    };<br>  });<br><br>  return (<br>    &lt;SharedElement id={sharedElementId}&gt;<br>      &lt;Animated.View style={animatedStyle}&gt;<br>        &lt;BaseButton style={{ flex: 1 }} onPress={onPress}&gt;<br>          &lt;Animated.Image style={imageStyle} source={imageSource} /&gt;<br>        &lt;/BaseButton&gt;<br>      &lt;/Animated.View&gt;<br>    &lt;/SharedElement&gt;<br>  );<br>};<br><br>export const Card = memo(CardInner);<br><br>const imageStyle = {<br>  width: CARD_WIDTH,<br>  height: CARD_HEIGHT,<br>  borderRadius: CARD_BORDER_RADIUS,<br>};</pre><p>I know there’s probably so much going on in these components. So let’s break it down.</p><p>We’ve already mentioned why we are using sharedElementId , now it&#39;s time to dive into how we are utilizing scrollY value in this component.</p><p><strong>Making the Cards Move with Your Scroll</strong></p><p>Now, to actually decide how the cards should move based on the scrolling, we use a technique called interpolation. This is just a fancy way of saying we translate the scroll distance into a specific movement for the cards. It’s like saying, “If our user scrolls this much, move the card up to here.”</p><p>Here’s a snippet that shows this in action:</p><pre>  const animatedStyle = useAnimatedStyle(() =&gt; {<br>    const animatedTop = interpolate(<br>      scrollY.value,<br>      [-50, 0, 50, 300], // This is how much you scroll<br>      mobileKeyCardTranslateYOutput, // This is how the card moves in response<br>      Extrapolation.CLAMP // This keeps the movement within limits we set<br>    );<br><br>    return {<br>      height: CARD_HEIGHT,<br>      width: CARD_WIDTH,<br>      borderRadius: CARD_BORDER_RADIUS,<br>      transform: [<br>        {<br>          translateY: withSpring(<br>            shouldDisplayAsStack ? i * animatedTop : 0,<br>            {<br>              damping: 15,<br>              mass: 0.8,<br>              stiffness: 100,<br>              overshootClamping: false,<br>              restDisplacementThreshold: 0.1,<br>              restSpeedThreshold: 0.1,<br>            }<br>          ),<br>        },<br>      ],<br>    };<br>  });</pre><p><strong>Making the Movement Feel Natural</strong></p><p>What makes the card movement feel smooth and kind of bouncy is using a spring animation for the translateY part. Unlike moving the card in a straight line, a spring animation lets the card move in a way that feels more like it&#39;s naturally responding to your touch.</p><pre>withSpring(<br>  shouldDisplayAsStack ? i * animatedTop : 0, // Decides how much to move the card<br>  {<br>    damping: 15,<br>    mass: 0.8,<br>    stiffness: 100,<br>    // There’s more settings here to tweak how the spring behaves<br>  }<br>);</pre><p>The shouldDisplayAsStack flag changes how the cards look based on your preference, stacking them like a deck of cards if true, or listing them normally if false.</p><p>Let’s perform a scroll action in our app to see how it looks with all these configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*iPiX10G-CudsTsz82OwRpQ.gif" /></figure><h4><strong>Bonus part — Card Detail Screen Animation</strong></h4><p>As the user scrolls, we want our card to scale up or down, adding depth and responsiveness. We achieve this with useAnimatedStyle from react-native-reanimated, adjusting the card style in response to the scrollY shared value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*M-Muynsg6-Jg7fKLCimPhQ.gif" /><figcaption>Card detail screen scroll animation</figcaption></figure><h4><strong>The Basics of Scaling on Scroll</strong></h4><p>The goal here is pretty straightforward: as the user scrolls, we want our card to scale up or down. This scaling gives a sense of depth and responsiveness, making the user’s interaction with the app feel more alive.</p><p>To get this done, we rely on useAnimatedStyle from react-native-reanimated. This hook lets us dynamically adjust the style of our card in response to the scroll position tracked by scrollY, a shared value.</p><p>Here’s the core part where we define the scaling:</p><pre>const animatedStyle = useAnimatedStyle(() =&gt; {<br>  const scale = interpolate(<br>    scrollY.value,<br>    [-210, -30, 0, 30, 210], // Scroll positions<br>    [1.05, 0.75, 0.7, 0.65, 0.4], // Corresponding scales<br>    Extrapolation.CLAMP<br>  );<br><br>  return {<br>    transform: [{ scale }],<br>  };<br>});</pre><p>In this snippet, interpolate figures out how much to scale the card based on the current scroll position. The scroll positions and corresponding scales are mapped to each other, meaning, for example, when you’ve scrolled 30 pixels down, the card scales down to 0.65 its original size. The Extrapolation.CLAMP ensures the scale doesn&#39;t go beyond the values we&#39;ve set, keeping everything looking smooth.</p><p>When all is said and done, what we have is a card that grows and shrinks as you move up and down the page. It’s a subtle touch, but it adds a lot to the overall feel of the app. By linking the visual scale of the card with the user’s scroll action, we make the experience feel more connected and dynamic.</p><h3>Conclusion</h3><p>In wrapping up, the essence of this guide was to explore how animations and transitions significantly enhance user experience.</p><blockquote>While react-native-reanimated offers a powerful suite for creating animations, including <a href="https://docs.swmansion.com/react-native-reanimated/docs/shared-element-transitions/overview/">shared element transitions</a>, I chose <a href="https://github.com/IjzerenHein/react-navigation-shared-element">react-navigation-shared-element</a> for this project due to the experimental status of shared element transitions in react-native-reanimated</blockquote><p>Going through the process of tweaking card components to move with your scrolling and making sure screen changes happen smoothly really drives home the point: it’s not all about flashy moves. Thoughtful animations do more than just catch the eye; they make the app feel like it’s listening and reacting to what you do. And it’s not solely about mimicking Apple Wallet animations, either. These ideas can be applied across a whole range of features to breathe life into any app.</p><p><a href="https://github.com/tarikfp/react-native-apple-wallet-animation">Final source code link</a></p><p>Don’t forget to follow me for more mobile development insights, particularly on React Native.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2faaf4dd10a4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/apple-wallet-animation-in-react-native-2faaf4dd10a4">Apple Wallet Animation In React Native</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Next Level Form Handling]]></title>
            <link>https://levelup.gitconnected.com/react-native-next-level-form-handling-25847b05191e?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/25847b05191e</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 05:01:11 GMT</pubDate>
            <atom:updated>2023-06-28T05:01:11.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Enhance Form Handling in React Native using Zod and React Hook Form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*pY99cC9jOgQvZlS-GoRcRg.png" /></figure><p>Form handling is a fundamental part of any application that requires user input, and with the right tools and libraries, it can be a simple and seamless process. This article will guide you on how to handle forms in a react-native app using the <a href="https://react-hook-form.com/"><strong>react-hook-form</strong></a> and <a href="https://zod.dev/"><strong>zod</strong></a>. By combining these two, we will achieve an efficient form handling mechanism. Let’s create a basic signup form to illustrate this.</p><p><strong><em>Full source code will be included at the end of the article.</em></strong></p><h4>Schema Declaration with Zod</h4><p>To begin with, we declare our schema using zod. This schema will lay out the expected shape of our form data and set up validations for each field. Zod provides a host of powerful validation functions to define these rules.</p><p>Here’s the full zod schema:</p><p>This article assumes that you know the basics of zod.</p><pre>import z from &#39;zod&#39;;<br><br>const phoneNumberRegexp = new RegExp(<br>  /^[\+]?([0-9][\s]?|[0-9]?)([(][0-9]{3}[)][\s]?|[0-9]{3}[-\s\.]?)[0-9]{3}[-\s\.]?[0-9]{4,6}$/im<br>);<br>const FIELD_REQUIRED_STR = &#39;This field is required&#39;;<br>export const GENDER_OPTIONS = [&#39;Male&#39;, &#39;Female&#39;, &#39;Other&#39;] as const;<br><br>export const signUpFormSchema = z.object({<br>  name: z<br>    .string({<br>      invalid_type_error: &#39;Name must be a string&#39;,<br>      required_error: FIELD_REQUIRED_STR,<br>    })<br>    .min(3, &#39;Minimum 3 characters&#39;)<br>    .max(20, &#39;Maximum 20 characters&#39;)<br>    .trim(),<br><br>  surname: z<br>    .string({<br>      invalid_type_error: &#39;Surname must be a string&#39;,<br>      required_error: FIELD_REQUIRED_STR,<br>    })<br>    .min(3, &#39;Minimum 3 characters&#39;)<br>    .max(20, &#39;Maximum 20 characters&#39;)<br>    .trim(),<br><br>  phoneNumber: z<br>    .string({<br>      invalid_type_error: &#39;Phone number must be a number&#39;,<br>      required_error: FIELD_REQUIRED_STR,<br>    })<br>    .regex(phoneNumberRegexp, &#39;Invalid phone number&#39;),<br><br>  email: z<br>    .string({<br>      invalid_type_error: &#39;Email must be a string&#39;,<br>      required_error: FIELD_REQUIRED_STR,<br>    })<br>    .email(&#39;Email is invalid&#39;),<br><br>  gender: z.enum(GENDER_OPTIONS, {<br>    required_error: FIELD_REQUIRED_STR,<br>    invalid_type_error: `Invalid gender, must be one of the followings: ${GENDER_OPTIONS.join(<br>      &#39;, &#39;<br>    )}`,<br>  }),<br><br>  birthDate: z<br>    .date({<br>      invalid_type_error: &#39;Birth date must be a date&#39;,<br>      required_error: FIELD_REQUIRED_STR,<br>    })<br>    .min(new Date(&#39;1900-01-01&#39;), &#39;Invalid date time, too old&#39;)<br>    .max(new Date(&#39;2023-01-01&#39;), &#39;Invalid date time, too young&#39;)<br>    .default(new Date()),<br>});<br><br>export type SignUpFormSchema = z.infer&lt;typeof signUpFormSchema&gt;;</pre><p>In this schema, we use zod to specify what each field should contain. For example, the name and surname fields should be strings between 3 to 20 characters long, while the phoneNumber field should be a number.</p><p>We also have more complex rules for some fields. For instance, the email field should be a string, and valid email addresses only. The gender field should be one of the predefined gender options (&#39;Male&#39;, &#39;Female&#39;, or &#39;Other&#39;).</p><p>Lastly, the birthDate field is of date type and should be a valid date between 1900-01-01 and 2023-01-01. By default, it takes the current date if none is provided.</p><p>With zod, we can create complex validation rules with ease. This way, the data we receive from our form will be guaranteed to match what we expect.</p><p>The next step is to infer the schema type. Zod offers an infer method, which derives the TypeScript type of a given zod schema.</p><pre>export type SignUpFormSchema = z.infer&lt;typeof signUpFormSchema&gt;;</pre><p>This inferred type is later on used in useForm to ensure that our form data aligns with our schema.</p><h4>Form Setup with React Hook Form</h4><p>Next, we set up our form using the useForm hook from &#39;react-hook-form&#39;. This hook takes our zod schema (through zodResolver) as an argument to resolve form validation.</p><pre>const methods = useForm&lt;SignUpFormSchema&gt;({<br>  resolver: zodResolver(signUpFormSchema),<br>  defaultValues: {<br>    birthDate: new Date(),<br>  },<br>  mode: &#39;onBlur&#39;,<br>});</pre><p>The resolver is where we pass our schema. The defaultValues property allows us to provide default values for form fields. In this case, we&#39;re setting the default birthDate to be the current date. The mode property dictates when validation should occur. In this case, validation will happen onBlur, or when the user moves away from a field.</p><h4>Field Rendering and Validation</h4><p>We use the Controller component from react-hook-form to manage each form field. It provides us with the field and fieldState props which we use to manage our field&#39;s value, error state, and validation.</p><p>For example, here’s how we set up the name field:</p><pre>&lt;Controller<br>  control={methods.control}<br>  name=&quot;name&quot;<br>  render={({<br>    field: { onChange, onBlur, value },<br>    fieldState: { error },<br>  }) =&gt; {<br>    return (<br>      &lt;TextInput<br>        label=&quot;Name&quot;<br>        onBlur={onBlur}<br>        value={value}<br>        onChangeText={onChange}<br>        errorMessage={error?.message}<br>      /&gt;<br>    );<br>  }}<br>/&gt;</pre><p>Here is what each prop does:</p><ul><li>control: This is where you pass the control prop from the useForm hook. It&#39;s necessary for the Controller to interact with the form state.</li><li>name: This is the key for accessing the value of the input within the form. When you retrieve form values or set values, this is the key that will be used. This must be unique across all form fields.</li><li>render: This is a function that returns your input element. The function provides field and fieldState props.</li><li>field: Contains onChange, onBlur, and value props. These should be directly linked to your controlled component. In this case, onChange is connected to onChangeText of TextInput, which will capture the user&#39;s input and store it in the form state.</li><li>fieldState: This includes the error prop that gives information about validation errors for this field.</li></ul><p>Inside the render prop, the TextInput is customized. onBlur and onChangeText are attached to the respective methods from the field, and value prop is linked to the current form value for this input. The errorMessage prop is wired to the error message in case of a validation failure.</p><p>So, in the case of form submission or real-time validation, if the ‘name’ field doesn’t fulfill the validation requirements defined in the Zod schema, the error message will be displayed in this TextInput field.</p><h4>Custom Validation Triggering with React Hook Form</h4><p>A unique scenario arises when dealing with the birthDate field, which uses a date picker component (in this case RNDateTimePicker). In this situation, the validation process requires special handling because the user&#39;s interaction with a date picker differs from typical text inputs.</p><pre>&lt;Controller<br>  control={methods.control}<br>  name=&quot;birthDate&quot;<br>  render={({ field: { onChange, onBlur, value }, fieldState: { error } }) =&gt; {<br>    return (<br>      &lt;View&gt;<br>        &lt;Text&gt;Birth date&lt;/Text&gt;<br>        &lt;RNDateTimePicker<br>          value={value}<br>          mode=&quot;date&quot;<br>          onChange={(e) =&gt; {<br>            if (e.type === &#39;set&#39; &amp;&amp; e.nativeEvent.timestamp) {<br>              onChange(new Date(e.nativeEvent.timestamp));<br>              methods.trigger(&#39;birthDate&#39;);<br>            }<br>          }}<br>        /&gt;<br>        {!!error?.message &amp;&amp; &lt;Text&gt;{error.message}&lt;/Text&gt;}<br>      &lt;/View&gt;<br>    );<br>  }}<br>/&gt;</pre><p>When the user selects a date, the onChange event is triggered. Inside this event handler, we first check if the event type is &#39;set&#39;, which indicates that the user has set a date. Next, we check if a timestamp is present, to ensure a date has been selected.</p><p>Upon confirming these conditions, we convert the timestamp to a JavaScript Date object using new Date(e.nativeEvent.timestamp). Then, this new value is passed to onChange, which updates the birthDate field&#39;s value in the form.</p><p>However, unlike typical text inputs that automatically trigger validation on changes, date pickers don’t trigger validation in the same way. Therefore, we need to manually trigger validation after the value is updated. We achieve this by calling methods.trigger(&#39;birthDate&#39;).</p><p>This trigger method provided by react-hook-form initiates validation for a specific field. Here, it triggers validation for the birthDate field as soon as the date is set, ensuring that our validation rules are applied immediately.</p><p>Finally, if there are any validation errors, they will be displayed via {!!error?.message &amp;&amp; &lt;Text&gt;{error.message}&lt;/Text&gt;}, where error?.message contains the validation error message as defined in our zod schema.</p><h4>Form Submission — React Hook Form</h4><p>React-hook-form package provides efficient methods to handle form submissions and error handling.</p><pre>const onSubmit: SubmitHandler&lt;SignUpFormSchema&gt; = (data) =&gt; {<br>  console.log(JSON.stringify(data));<br>};<br><br>const onError: SubmitErrorHandler&lt;SignUpFormSchema&gt; = (<br>  errors,<br>  e<br>) =&gt; {<br>  console.log(JSON.stringify(errors));<br>};<br><br>&lt;Button<br>  onPress={methods.handleSubmit(onSubmit, onError)}<br>  title=&quot;Submit Form&quot;<br>  color={&#39;#007BFF&#39;}<br>/&gt;</pre><p>Let’s break down the process:</p><p>The onSubmit handler receives the form data as its argument. In this scenario, we&#39;re merely logging this data, but in real-world applications, it could be sent to a server or manipulated further based on the needs of the application.</p><p>The onError function, however, is invoked when there are validation errors upon form submission. The errors object contains detailed information about all fields that failed validation. In this example, we&#39;re simply logging these errors.</p><p>In case of every field has an error, then the error object would be the following:</p><pre>{<br>  &quot;name&quot;: {<br>    &quot;message&quot;: &quot;This field is required&quot;,<br>    &quot;type&quot;: &quot;invalid_type&quot;,<br>    &quot;ref&quot;: {<br>      &quot;name&quot;: &quot;name&quot;<br>    }<br>  },<br>  &quot;surname&quot;: {<br>    &quot;message&quot;: &quot;This field is required&quot;,<br>    &quot;type&quot;: &quot;invalid_type&quot;,<br>    &quot;ref&quot;: {<br>      &quot;name&quot;: &quot;surname&quot;<br>    }<br>  },<br>  &quot;phoneNumber&quot;: {<br>    &quot;message&quot;: &quot;This field is required&quot;,<br>    &quot;type&quot;: &quot;invalid_type&quot;,<br>    &quot;ref&quot;: {<br>      &quot;name&quot;: &quot;phoneNumber&quot;<br>    }<br>  },<br>  &quot;email&quot;: {<br>    &quot;message&quot;: &quot;This field is required&quot;,<br>    &quot;type&quot;: &quot;invalid_type&quot;,<br>    &quot;ref&quot;: {<br>      &quot;name&quot;: &quot;email&quot;<br>    }<br>  },<br>  &quot;gender&quot;: {<br>    &quot;message&quot;: &quot;This field is required&quot;,<br>    &quot;type&quot;: &quot;invalid_type&quot;,<br>    &quot;ref&quot;: {<br>      &quot;name&quot;: &quot;gender&quot;<br>    }<br>  },<br>  &quot;birthDate&quot;: {<br>    &quot;message&quot;: &quot;Invalid date time, too young&quot;,<br>    &quot;type&quot;: &quot;too_big&quot;,<br>    &quot;ref&quot;: {<br>      &quot;name&quot;: &quot;birthDate&quot;<br>    }<br>  }<br>}</pre><h4>Pre-validation with Zod</h4><p>The provided code block below presents an approach of manually pre-validating form data using Zod’s safeParse method before the form submission event. Although the form validation is already taken care of by the handleSubmit method from React Hook Form, pre-validation can give developers more control over the form validation process.</p><pre>&lt;Button<br>  title=&quot;Submit Form&quot;<br>  onPress={() =&gt; {<br>    // get current form values<br>    const currFormValues = methods.getValues();<br><br>    // Prevalidate using zod&#39;s safeParse<br>    const result = signUpFormSchema.safeParse(currFormValues);<br><br>    // If prevalidation is failed, display the error<br>    if (!result.success) {<br>      Alert.alert(JSON.stringify(result.error));<br>    } else {<br>      // If prevalidation is successful, notify the user<br>      Alert.alert(&#39;Validation is successful with zod&#39;);<br>    }<br>  }}<br>/&gt;</pre><p>Let’s analyze the code above:</p><ul><li>The onPress event for the Button is being used to execute a function that performs pre-validation before form submission.</li><li>The getValues method from methods (which is provided by React Hook Form) is used to retrieve the current form values.</li><li>These values are then passed to the safeParse method from the signUpFormSchema (a zod schema that we created in the beginning). This step is where zod pre-validation happens. Unlike zod parse method, safeParse does not throw an error when the validation fails. Instead, it returns an object containing the success boolean and, if the validation failed, an error object.</li><li>A conditional statement checks if result.success is false (indicating that the validation failed). If it&#39;s false, it triggers an alert displaying the validation error.</li><li>If result.success is true (indicating successful validation), it triggers an alert stating that the validation was successful with zod.</li></ul><p>Even though this approach might seem redundant because React Hook Form’s handleSubmit already performs the form validation using the schema provided via zod, it can still be beneficial in specific scenarios. For instance, you might want to perform certain actions only after manual validation, or you might want to validate form inputs in real-time as the user fills out the form. In such cases, pre-validation using zod safeParse method can be quite useful.</p><p>And this is how zod error object would look like:</p><pre>{<br>  &quot;issues&quot;: [<br>    {<br>      &quot;code&quot;: &quot;invalid_type&quot;,<br>      &quot;expected&quot;: &quot;string&quot;,<br>      &quot;received&quot;: &quot;undefined&quot;,<br>      &quot;path&quot;: [<br>        &quot;name&quot;<br>      ],<br>      &quot;message&quot;: &quot;This field is required&quot;<br>    },<br>    {<br>      &quot;code&quot;: &quot;invalid_type&quot;,<br>      &quot;expected&quot;: &quot;string&quot;,<br>      &quot;received&quot;: &quot;undefined&quot;,<br>      &quot;path&quot;: [<br>        &quot;surname&quot;<br>      ],<br>      &quot;message&quot;: &quot;This field is required&quot;<br>    },<br>    {<br>      &quot;code&quot;: &quot;invalid_type&quot;,<br>      &quot;expected&quot;: &quot;string&quot;,<br>      &quot;received&quot;: &quot;undefined&quot;,<br>      &quot;path&quot;: [<br>        &quot;phoneNumber&quot;<br>      ],<br>      &quot;message&quot;: &quot;This field is required&quot;<br>    },<br>    {<br>      &quot;code&quot;: &quot;invalid_type&quot;,<br>      &quot;expected&quot;: &quot;string&quot;,<br>      &quot;received&quot;: &quot;undefined&quot;,<br>      &quot;path&quot;: [<br>        &quot;email&quot;<br>      ],<br>      &quot;message&quot;: &quot;This field is required&quot;<br>    },<br>    {<br>      &quot;expected&quot;: &quot;&#39;Male&#39; | &#39;Female&#39; | &#39;Other&#39;&quot;,<br>      &quot;received&quot;: &quot;undefined&quot;,<br>      &quot;code&quot;: &quot;invalid_type&quot;,<br>      &quot;path&quot;: [<br>        &quot;gender&quot;<br>      ],<br>      &quot;message&quot;: &quot;This field is required&quot;<br>    },<br>    {<br>      &quot;code&quot;: &quot;too_big&quot;,<br>      &quot;message&quot;: &quot;Invalid date time, too young&quot;,<br>      &quot;inclusive&quot;: true,<br>      &quot;exact&quot;: false,<br>      &quot;maximum&quot;: 1672531200000,<br>      &quot;type&quot;: &quot;date&quot;,<br>      &quot;path&quot;: [<br>        &quot;birthDate&quot;<br>      ]<br>    }<br>  ],<br>  &quot;name&quot;: &quot;ZodError&quot;<br>}</pre><p>Its indeed a large object, and there might be even unnecessary fields for our case. Luckily, zod provides a method for <a href="https://zod.dev/?id=error-formatting">formatting errors</a>.</p><p>We can simply use result.error.format() and the rest will be handled internally by zod.</p><pre><br>    if (!result.success) {<br>      // Format errors using result.error.format()<br>      const formattedError = result.error.format();<br>      Alert.alert(JSON.stringify(formattedError));<br>    } else {<br>      Alert.alert(&#39;Validation is successful with zod&#39;);<br>    }</pre><p>Formatted error object would like the following:</p><pre>{<br>  &quot;name&quot;: {<br>    &quot;_errors&quot;: [<br>      &quot;This field is required&quot;<br>    ]<br>  },<br>  &quot;surname&quot;: {<br>    &quot;_errors&quot;: [<br>      &quot;This field is required&quot;<br>    ]<br>  },<br>  &quot;phoneNumber&quot;: {<br>    &quot;_errors&quot;: [<br>      &quot;This field is required&quot;<br>    ]<br>  },<br>  &quot;email&quot;: {<br>    &quot;_errors&quot;: [<br>      &quot;This field is required&quot;<br>    ]<br>  },<br>  &quot;gender&quot;: {<br>    &quot;_errors&quot;: [<br>      &quot;This field is required&quot;<br>    ]<br>  },<br>  &quot;birthDate&quot;: {<br>    &quot;_errors&quot;: [<br>      &quot;Invalid date time, too young&quot;<br>    ]<br>  }<br>}</pre><h4>The latest code</h4><p>The following is the most recent code (excluding imports and styles). If you wish to view the complete source code, please refer to the end of the article.</p><pre>// imports...<br><br>export const SignupForm: React.FC = () =&gt; {<br>  const [shouldValidateWithZod, setShouldValidateWithZod] =<br>    React.useState&lt;boolean&gt;(false);<br><br>  const [isCalendarOpenForAndroid, setIsCalendarOpenForAndroid] =<br>    React.useState&lt;boolean&gt;(false);<br><br>  const methods = useForm&lt;SignUpFormSchema&gt;({<br>    resolver: zodResolver(signUpFormSchema),<br>    defaultValues: {<br>      birthDate: new Date(),<br>    },<br>    mode: &#39;onBlur&#39;,<br>  });<br><br>  const onSubmit: SubmitHandler&lt;SignUpFormSchema&gt; = (data) =&gt; {<br>    console.log(JSON.stringify(data));<br>  };<br><br>  const onError: SubmitErrorHandler&lt;SignUpFormSchema&gt; = (<br>    errors,<br>    e<br>  ) =&gt; {<br>    console.log(JSON.stringify(errors));<br>    Alert.alert(&#39;Warning&#39;, getReadableValidationErrorMessage(errors));<br>  };<br><br>  return (<br>    &lt;SafeAreaView edges={[&#39;top&#39;, &#39;bottom&#39;]} style={styles.safeArea}&gt;<br>      &lt;ScrollView&gt;<br>        &lt;Text style={styles.title}&gt;Sign Up Form&lt;/Text&gt;<br>        &lt;View style={styles.root}&gt;<br>          &lt;FormProvider {...methods}&gt;<br>            &lt;Controller<br>              control={methods.control}<br>              name=&quot;name&quot;<br>              render={({<br>                field: { onChange, onBlur, value },<br>                fieldState: { error },<br>              }) =&gt; {<br>                return (<br>                  &lt;TextInput<br>                    label=&quot;Name&quot;<br>                    onBlur={onBlur}<br>                    value={value}<br>                    onChangeText={onChange}<br>                    errorMessage={error?.message}<br>                  /&gt;<br>                );<br>              }}<br>            /&gt;<br>            &lt;View style={styles.spacing} /&gt;<br>            &lt;Controller<br>              control={methods.control}<br>              name=&quot;surname&quot;<br>              render={({<br>                field: { onChange, onBlur, value },<br>                fieldState: { error },<br>              }) =&gt; {<br>                return (<br>                  &lt;TextInput<br>                    label=&quot;Surname&quot;<br>                    onBlur={onBlur}<br>                    value={value}<br>                    onChangeText={onChange}<br>                    errorMessage={error?.message}<br>                  /&gt;<br>                );<br>              }}<br>            /&gt;<br>            &lt;View style={styles.spacing} /&gt;<br><br>            &lt;Controller<br>              control={methods.control}<br>              name=&quot;email&quot;<br>              render={({<br>                field: { onChange, onBlur, value },<br>                fieldState: { error },<br>              }) =&gt; {<br>                return (<br>                  &lt;TextInput<br>                    label=&quot;Email&quot;<br>                    onBlur={onBlur}<br>                    value={value}<br>                    onChangeText={onChange}<br>                    errorMessage={error?.message}<br>                  /&gt;<br>                );<br>              }}<br>            /&gt;<br><br>            &lt;View style={styles.spacing} /&gt;<br><br>            &lt;Controller<br>              control={methods.control}<br>              name=&quot;phoneNumber&quot;<br>              render={({<br>                field: { onChange, onBlur, value },<br>                fieldState: { error },<br>              }) =&gt; {<br>                return (<br>                  &lt;TextInput<br>                    label=&quot;Phone number&quot;<br>                    onBlur={onBlur}<br>                    keyboardType=&quot;decimal-pad&quot;<br>                    value={value}<br>                    onChangeText={(val) =&gt; onChange(val.toString())}<br>                    errorMessage={error?.message}<br>                  /&gt;<br>                );<br>              }}<br>            /&gt;<br><br>            &lt;View style={styles.spacing} /&gt;<br><br>            &lt;Controller<br>              control={methods.control}<br>              name=&quot;birthDate&quot;<br>              render={({<br>                field: { onChange, value },<br>                fieldState: { error },<br>              }) =&gt; {<br>                return (<br>                  &lt;View style={styles.dateWrapper}&gt;<br>                    &lt;Text style={styles.label}&gt;Birth date&lt;/Text&gt;<br><br>                    {Platform.OS === &#39;android&#39; &amp;&amp; (<br>                      &lt;Button<br>                        onPress={() =&gt; {<br>                          setIsCalendarOpenForAndroid(true);<br>                        }}<br>                        title={value.toString()}<br>                      /&gt;<br>                    )}<br><br>                    {(isCalendarOpenForAndroid ||<br>                      Platform.OS !== &#39;android&#39;) &amp;&amp; (<br>                      &lt;RNDateTimePicker<br>                        value={value}<br>                        style={styles.dateTimePicker}<br>                        mode={&#39;date&#39;}<br>                        onChange={(e) =&gt; {<br>                          if (Platform.OS === &#39;android&#39;) {<br>                            setIsCalendarOpenForAndroid(false);<br>                          }<br><br>                          if (<br>                            e.type === &#39;set&#39; &amp;&amp;<br>                            e.nativeEvent.timestamp<br>                          ) {<br>                            onChange(<br>                              new Date(e.nativeEvent.timestamp)<br>                            );<br>                            methods.trigger(&#39;birthDate&#39;);<br>                          }<br>                        }}<br>                      /&gt;<br>                    )}<br><br>                    {!!error?.message &amp;&amp; (<br>                      &lt;Text style={styles.errorMessageText}&gt;<br>                        {error.message}<br>                      &lt;/Text&gt;<br>                    )}<br>                  &lt;/View&gt;<br>                );<br>              }}<br>            /&gt;<br><br>            &lt;View style={styles.spacing} /&gt;<br><br>            &lt;Controller<br>              control={methods.control}<br>              name=&quot;gender&quot;<br>              render={({<br>                field: { onChange, onBlur, value, ref },<br>                fieldState: { error },<br>              }) =&gt; {<br>                return (<br>                  &lt;View style={styles.genderWrapper}&gt;<br>                    &lt;Text style={styles.label}&gt;Gender&lt;/Text&gt;<br>                    &lt;View style={styles.genderOptionsWrapper}&gt;<br>                      {GENDER_OPTIONS.map((genderOption) =&gt; (<br>                        &lt;Pressable<br>                          key={genderOption}<br>                          style={[<br>                            styles.genderOptionPressable,<br>                            {<br>                              backgroundColor:<br>                                value === genderOption<br>                                  ? &#39;#007BFF&#39;<br>                                  : &#39;#F2F2F2&#39;,<br>                            },<br>                          ]}<br>                          onPress={() =&gt; onChange(genderOption)}<br>                        &gt;<br>                          &lt;Text<br>                            style={[<br>                              styles.genderOptionText,<br>                              {<br>                                color:<br>                                  value === genderOption<br>                                    ? &#39;#fff&#39;<br>                                    : &#39;#000&#39;,<br>                              },<br>                            ]}<br>                          &gt;<br>                            {genderOption}<br>                          &lt;/Text&gt;<br>                        &lt;/Pressable&gt;<br>                      ))}<br>                    &lt;/View&gt;<br>                    {!!error?.message &amp;&amp; (<br>                      &lt;Text style={styles.errorMessageText}&gt;<br>                        {error.message}<br>                      &lt;/Text&gt;<br>                    )}<br>                  &lt;/View&gt;<br>                );<br>              }}<br>            /&gt;<br><br>            &lt;View style={styles.spacing} /&gt;<br><br>            &lt;Text style={styles.label}&gt;Should validate with zod&lt;/Text&gt;<br><br>            &lt;Switch<br>              value={shouldValidateWithZod}<br>              onChange={(e) =&gt;<br>                setShouldValidateWithZod(e.nativeEvent.value)<br>              }<br>            /&gt;<br>            &lt;View style={styles.spacing} /&gt;<br><br>            &lt;Button<br>              onPress={<br>                shouldValidateWithZod<br>                  ? () =&gt; {<br>                      /** we could also prevalidate using zod like below */<br><br>                      // get current form values<br>                      const currFormValues = methods.getValues();<br>                      // https://zod.dev/?id=safeparse<br>                      const result =<br>                        signUpFormSchema.safeParse(currFormValues);<br><br>                      if (!result.success) {<br>                        const formattedError = result.error.format();<br>                        Alert.alert(JSON.stringify(formattedError));<br>                      } else {<br>                        Alert.alert(<br>                          &#39;Validation is successful with zod&#39;<br>                        );<br>                      }<br>                    }<br>                  : methods.handleSubmit(onSubmit, onError)<br>              }<br>              title=&quot;Submit Form&quot;<br>              color={&#39;#007BFF&#39;}<br>            /&gt;<br>          &lt;/FormProvider&gt;<br>        &lt;/View&gt;<br>      &lt;/ScrollView&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>};<br><br><br>// styles...</pre><p>This sample app is written using <a href="https://expo.dev/client">expo go</a>. Meaning you can easily test it using the QR code below! <em>(in case the QR does not work, please refer to the source code link at the end of the article.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*64aqLz3tRQIFDm3ZXbvIdw.png" /></figure><h4>Conclusion</h4><p>Throughout this article, we have explored how we can effectively leverage the combination of React Hook Form, Zod, and TypeScript to create robust form validation in our React Native application. We’ve seen how the flexibility and power of these libraries enable us to produce clean, type-safe code that can handle complex validation requirements.</p><p>The synergy of React Hook Form and Zod allows us to reap the benefits of both. React Hook Form simplifies form handling, optimizes re-rendering, and includes features such as form state management and error handling. On the other hand, Zod provides an extra layer of safety, allowing us to specify what kind of data is allowed for each form field and to enforce these rules.</p><p>Remember, while the techniques shown here are used within the context of a simple SignUp form, they are applicable to any form-based user input in your React Native applications. By employing these strategies, you can ensure your forms are user-friendly, robust, and maintainable, leading to better user experiences and more robust applications.</p><p><a href="https://github.com/tarikpnr/rn-zod-react-hook-form"><strong>Full source code link</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25847b05191e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/react-native-next-level-form-handling-25847b05191e">React Native Next Level Form Handling</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Tabbar and Navigation Controller Programmatically in UIKit]]></title>
            <link>https://levelup.gitconnected.com/creating-tabbar-and-navigation-controller-programmatically-in-uikit-3c385cc988b7?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c385cc988b7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Thu, 11 May 2023 14:36:46 GMT</pubDate>
            <atom:updated>2023-05-12T16:19:30.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*W2QwC8EUjUxSKHCPmOT-xQ.png" /><figcaption>Image from: <a href="https://developer.apple.com/documentation/uikit/uitabbarcontroller#1653005">https://developer.apple.com/documentation/uikit/uitabbarcontroller#1653005</a></figcaption></figure><p>I have always been inclined towards adopting a programmatic approach when developing iOS mobile apps with UIKit. While storyboards may initially appear convenient, they tend to make me feel more like a designer than a programmer. Moreover, when it comes to scalability and manageability, I consistently find the programmatic approach to be superior.</p><p>Within the scope of this article, I will elaborate on the process of creating a tab bar controller combined with a navigation controller using UIKit.</p><h4>Setting up SceneDelegate</h4><p>The initial step in adopting a programmatic approach is to modify the root code of our application. I call it “root” and it reminds me App.js or index.jsin React/React Native. This serves as the entry point for our application or scene. In iOS, we can find a scene function within the SceneDelegateclass, which we will solely utilize to configure our application for programmatic development.</p><p>Below is the default structure of the SceneDelegateclass:</p><pre>import UIKit<br><br>class SceneDelegate: UIResponder, UIWindowSceneDelegate {<br><br>  var window: UIWindow?<br><br><br>  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.<br>    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.<br>    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).<br>    guard let _ = (scene as? UIWindowScene) else { return }<br>  }<br><br>  func sceneDidDisconnect(_ scene: UIScene) {<br>    // Called as the scene is being released by the system.<br>    // This occurs shortly after the scene enters the background, or when its session is discarded.<br>    // Release any resources associated with this scene that can be re-created the next time the scene connects.<br>    // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).<br>  }<br><br>  func sceneDidBecomeActive(_ scene: UIScene) {<br>    // Called when the scene has moved from an inactive state to an active state.<br>    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.<br>  }<br><br>  func sceneWillResignActive(_ scene: UIScene) {<br>    // Called when the scene will move from an active state to an inactive state.<br>    // This may occur due to temporary interruptions (ex. an incoming phone call).<br>  }<br><br>  func sceneWillEnterForeground(_ scene: UIScene) {<br>    // Called as the scene transitions from the background to the foreground.<br>    // Use this method to undo the changes made on entering the background.<br>  }<br><br>  func sceneDidEnterBackground(_ scene: UIScene) {<br>    // Called as the scene transitions from the foreground to the background.<br>    // Use this method to save data, release shared resources, and store enough scene-specific state information<br>    // to restore the scene back to its current state.<br>  }<br><br><br>}</pre><p>We will only be updating the function below:</p><pre>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.<br>    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.<br>    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).<br>    guard let _ = (scene as? UIWindowScene) else { return }<br>  }</pre><h4>Updating scene function in SceneDelegate</h4><p>In the following code snippet, we ensure the safe retrieval of the windowSceneusing the guard statement. Subsequently, we assign this windowSceneto the window property, which is defined within the SceneDelegate class. Finally, we invoke the makeKeyAndVisible method to make the window the key window.</p><pre>var window: UIWindow?<br><br>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>    guard let windowScene = (scene as? UIWindowScene) else { return }<br>    window?.windowScene = windowScene<br>    window?.makeKeyAndVisible()<br>  }</pre><p>Next, let’s focus on creating the tab bar controller. This controller will handle the view controllers for each tab in our app. <strong><em>For example, if we have two tabs, we’ll need two separate navigation controllers.</em></strong> But why do we choose navigation controllers? Well, it’s because we want to have our own navigation controller within each tab. Let’s take the “Profile” tab as an example. The profile screen will be the main view for that tab, but we may have additional views within the tab that we want to navigate between. That’s why we use navigation controllers for each tab item. They provide the necessary functionality to navigate smoothly between different view controllers within a tab.</p><p>Let’s code this!</p><pre> func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>    guard let windowScene = (scene as? UIWindowScene) else { return }<br>    window?.windowScene = windowScene<br>    window?.makeKeyAndVisible()<br><br>    let tabbar = UITabBarController()<br>    <br>    let firstVC = UINavigationController(rootViewController: ViewController())<br>    let secondVC = UINavigationController(rootViewController: SecondViewController())<br><br>    <br>    firstVC.tabBarItem = UITabBarItem(title: &quot;Home&quot;, image: UIImage(systemName: &quot;house&quot;),selectedImage: UIImage(systemName: &quot;house.fill&quot;))<br>    secondVC.tabBarItem = UITabBarItem(title: &quot;Profile&quot;, image: UIImage(systemName: &quot;person&quot;),selectedImage: UIImage(systemName: &quot;person.fill&quot;))<br><br>    tabbar.viewControllers = [firstVC, secondVC]<br><br>    window?.rootViewController = tabbar<br><br>  }</pre><p>After initializing our tab bar controller, we proceed to create two navigation controllers, which correspond to the two tab items in our app. The first view controller is the default one, while the second view controller, known as SecondViewController, will be covered in the next section. SecondViewControlleris a regular view controller similar to the default one.</p><p>To configure the tab items, we set the tabItem property of each navigation controller using UITabBarItem.</p><p>Finally, we assign the created view controllers to the tab bar controller’s viewControllers property.</p><p>And the most crucial step is setting the window&#39;s rootViewController as our tab bar controller. This ensures that the tab bar, along with the navigation controllers within each tab item, resides at the top of our app&#39;s hierarchy.</p><h4>View Controllers in action</h4><p>Let&#39;s take a look at our ViewController class below:</p><pre>class ViewController: UIViewController {<br><br>  override func viewDidLoad() {<br>    super.viewDidLoad()<br>    setupUI()<br>  }<br><br>  func setupUI(){<br>    view.backgroundColor = .white<br><br>    let homeLabel: UILabel = {<br>      let label = UILabel()<br>      label.text = &quot;This is home screen&quot;<br>      label.translatesAutoresizingMaskIntoConstraints = false<br>      return label<br>    }()<br><br>    let homeButton: UIButton = {<br>      let button = UIButton()<br>      button.setTitle(&quot;Go to profile&quot;, for: .normal)<br>      button.setTitleColor(.white, for: .normal)<br>      button.backgroundColor = .systemOrange<br>      button.translatesAutoresizingMaskIntoConstraints = false<br>      button.addTarget(self, action: #selector(goToProfile), for: .touchUpInside)<br>      return button<br>    }()<br><br>    view.addSubview(homeButton)<br>    view.addSubview(homeLabel)<br><br>   <br>    NSLayoutConstraint.activate([<br>      homeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),<br>      homeButton.widthAnchor.constraint(equalTo: view.widthAnchor), <br>      homeButton.heightAnchor.constraint(equalToConstant: 72), <br>      homeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), <br>      homeLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)<br>    ])<br><br>  }<br><br>  @objc func goToProfile(){<br>    tabBarController?.selectedIndex = 1<br>  }<br><br>}</pre><p>And, SecondViewController(<em>I know right, poor naming convention here…</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*38H_rYXGqsbZNlvJXlyWpg.gif" /><figcaption>“SecondViewController”</figcaption></figure><pre><br>class SecondViewController: UIViewController {<br>  override func viewDidLoad() {<br>    super.viewDidLoad()<br>    setupUI()<br>  }<br><br>  func setupUI(){<br>    view.backgroundColor = .white<br><br>    let profileLabel: UILabel = {<br>      let label = UILabel()<br>      label.translatesAutoresizingMaskIntoConstraints = false<br>      label.text = &quot;This is profile screen&quot;<br>      return label<br>    }()<br><br>    let profileButton: UIButton = {<br>      let button = UIButton()<br>      button.setTitle(&quot;Go to home&quot;, for: .normal)<br>      button.setTitleColor(.white, for: .normal)<br>      button.backgroundColor = .systemOrange<br>      button.translatesAutoresizingMaskIntoConstraints = false<br>      button.addTarget(self, action: #selector(goToHome), for: .touchUpInside)<br>      return button<br>    }()<br><br>    view.addSubview(profileButton)<br>    view.addSubview(profileLabel)<br><br>    NSLayoutConstraint.activate([<br>      homeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),<br>      homeButton.widthAnchor.constraint(equalTo: view.widthAnchor), <br>      homeButton.heightAnchor.constraint(equalToConstant: 72), <br>      homeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), <br>      homeLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)<br>    ])<br><br>  }<br><br>  @objc func goToHome(){<br>    tabBarController?.selectedIndex = 0<br>  }<br><br>}</pre><blockquote>Obviously, the code is just quite repetitive. But it can be neglected for the purpose of this article.</blockquote><p>These two view controllers are essentially identical, except for their titles and button actions. Both controllers primarily render a label in the center of the screen, describing the name of the current screen. Additionally, they feature a button at the bottom of the screen, enabling navigation between tab items. That summarizes the core functionality of these view controllers.</p><h4>Latest picture</h4><p>We have now a fully programmatic app that utilizes tab bar and navigation controller, without 0 storyboard!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Mh9-aPrme1BRh4QRjRhkVw.gif" /><figcaption>Indeed ugly but functional</figcaption></figure><h4>Conclusion</h4><p>In conclusion, adopting a programmatic approach provides greater control over the app’s design and scalability, allowing developers to focus on the programming aspect rather than solely relying on storyboards. Specifically for IBAction/IBOutlet Issues<strong>. </strong>One particular issue that arises when refactoring code involving IBOutlet and IBAction variables is the need to reestablish connections after making changes. In my experience, after a few days of working on the codebase, I encountered unexpected crashes in the app without any clear explanation. Upon further investigation, I discovered that the cause of these crashes was the renamed IBOutlet and IBAction variable names. Each time this occurred, I had to manually reconnect the affected variables to restore their functionality. This can be a time-consuming and frustrating process, disrupting the development workflow.</p><p>Thanks for reading!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c385cc988b7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-tabbar-and-navigation-controller-programmatically-in-uikit-3c385cc988b7">Creating Tabbar and Navigation Controller Programmatically in UIKit</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Native with React-Query and Zustand]]></title>
            <link>https://levelup.gitconnected.com/testing-react-native-with-react-query-and-zustand-d957c2a40b73?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d957c2a40b73</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 17:47:00 GMT</pubDate>
            <atom:updated>2023-07-03T16:14:02.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*boj1QwmVIieAzDLnNaD63w.png" /></figure><p>React Native has become a popular choice for building mobile applications due to its fast development cycle and cross-platform compatibility. To make the most out of React Native development, developers often turn to third-party libraries like React-Query and Zustand to handle data fetching and state management. React-Query provides a flexible and efficient way to fetch, cache, and manage your data, while Zustand makes state management simple and powerful with its minimalist approach.</p><p>In this article, we will explore how to effectively test React Native applications that use these two libraries. We will be using a simple store app as an example and will provide comprehensive and detailed examples to help you understand the testing process. By the end of this article, you will have a good understanding of how to use and test React-Query and Zustand in your React Native apps</p><h4>1 — Setting up the environment</h4><p>We will be using React Native version <strong><em>0.71.2</em></strong> to initialize our store app and React-Query(Tanstack query) version <strong><em>3.39.3</em></strong> and Zustand version <strong><em>4.3.2</em></strong> to handle data fetching and state management. I will provide the full source code for the complete app on GitHub, so if you want to jump in and see it in action, you can do so by <a href="#8fa3">accessing the link which is shared at the end of the article</a>. This will allow you to follow along with the examples and see the complete code for the app.</p><h4>1.1 — Setting up store API</h4><p>We will be using <a href="https://fakestoreapi.com/">https://fakestoreapi.com</a> as our API to demonstrate effective testing techniques in React Native. Our store app will fetch a set of products from this API and provide a detailed view of each product. Although the FakeStoreProduct has other REST APIs that we could utilize, doing so would increase complexity and detract from the primary objective of this article.</p><p>To communicate with our API across our app, we will create an axios instance.</p><h4>1.2— Setup axios instance</h4><pre>import axios from &#39;axios&#39;;<br><br>export const BASE_URL = &#39;https://fakestoreapi.com&#39;;<br><br>export const api = axios.create({<br>  baseURL: BASE_URL,<br>});</pre><p>Next steps will be creating our react-query setup for our API.</p><h4>1.3 — Create the key-factory for managing query caching</h4><p>What is key-factory?</p><p><a href="https://tanstack.com/query/latest/docs/react/guides/query-keys"><em>At its core, TanStack Query manages query caching for you based on query keys. Query keys have to be an Array at the top level, and can be as simple as an Array with a single string, or as complex as an array of many strings and nested objects. As long as the query key is serializable, and unique to the query’s data, you can use it!</em></a></p><p>Although the simplicity of our app does not necessarily require the use of caching, we will be utilizing React-Query’s powerful caching features nonetheless. Thus, we will be creating a simple key factory, which will be demonstrated below.</p><pre>export const productKeyFactory = {<br>  products: [&#39;all-products&#39;],<br>  productById: (id: number) =&gt; [...productKeyFactory.products, id],<br>} as const;</pre><h4>1.4— Fetching products using react-query</h4><pre>import {AxiosError} from &#39;axios&#39;;<br>import {useQuery, UseQueryOptions} from &#39;react-query&#39;;<br>import {api} from &#39;../axios.instance&#39;;<br>import {productKeyFactory} from &#39;./key-factory&#39;;<br>import {Product} from &#39;./types&#39;;<br><br>export const getAllProducts = async () =&gt; {<br>  return (await api.get&lt;Array&lt;Product&gt;&gt;(&#39;/products&#39;)).data;<br>};<br><br>export const useGetAllProducts = (<br>  options?: UseQueryOptions&lt;<br>    Array&lt;Product&gt;,<br>    AxiosError,<br>    Array&lt;Product&gt;,<br>    readonly [string]<br>  &gt;,<br>) =&gt; {<br>  return useQuery({<br>    queryKey: [...productKeyFactory.products],<br>    queryFn: getAllProducts,<br>    ...options,<br>  });<br>};</pre><p>Above, we’ve created useGetAllProducts hook for fetching the products, as well as utilizing the query-key we created in the previous section.</p><h4>1.5 — Fetching product detail using react-query</h4><pre>import {AxiosError} from &#39;axios&#39;;<br>import {useQuery, UseQueryOptions} from &#39;react-query&#39;;<br>import {api} from &#39;../axios.instance&#39;;<br>import {productKeyFactory} from &#39;./key-factory&#39;;<br>import {Product} from &#39;./types&#39;;<br><br>export const getProductById = async (productId: number) =&gt; {<br>  return (await api.get&lt;Product&gt;(`/products/${productId}`)).data;<br>};<br><br>export const useGetProductById = (<br>  productId: number,<br>  options?: UseQueryOptions&lt;<br>    Product,<br>    AxiosError,<br>    Product,<br>    readonly (string | number)[]<br>  &gt;,<br>) =&gt; {<br>  return useQuery({<br>    queryFn: () =&gt; getProductById(productId),<br>    queryKey: [...productKeyFactory.productById(productId)],<br>    ...options,<br>  });<br>};</pre><p>Almost the same as the previous hook, except this timeuseGetProductById hook will be used for fetching the product’s detail by its id.</p><h4>1.6— Product type</h4><p>Let’s not skip to get an idea of how the product object does look.</p><pre>export interface Product {<br>  id: number;<br>  title: string;<br>  price: number;<br>  description: string;<br>  category: string;<br>  image: string;<br>  rating: Rating;<br>}<br><br>export interface Rating {<br>  rate: number;<br>  count: number;<br>}</pre><h4>1.7 — Here comes zustand, managing products in the basket</h4><p>The app will include basic features that allow users to add or remove products from their basket, as well as adjust the quantity of individual products. Additionally, users have the ability to reset the entire basket. These functionalities will be managed using Zustand. Below, we will examine its implementation.</p><pre>import {create} from &#39;zustand&#39;;<br>import {shallow} from &#39;zustand/shallow&#39;;<br>import {Product} from &#39;../api/product&#39;;<br><br>export type ProductInBasket = {<br>  product: Product;<br>  quantity: number;<br>};<br><br>export const updateProductQuantity = (<br>  productsInBasket: Array&lt;ProductInBasket&gt;,<br>  productId: number,<br>  updateType: &#39;increase&#39; | &#39;decrease&#39;,<br>) =&gt; {<br>  return productsInBasket.map(productInBasket =&gt; {<br>    if (productInBasket.product.id === productId) {<br>      return {<br>        ...productInBasket,<br>        quantity:<br>          updateType === &#39;increase&#39;<br>            ? productInBasket.quantity + 1<br>            : productInBasket.quantity - 1,<br>      };<br>    }<br>    return productInBasket;<br>  });<br>};<br><br>export const increaseProductQuantityInBasket = (<br>  productsInBasket: Array&lt;ProductInBasket&gt;,<br>  productId: number,<br>) =&gt; {<br>  return updateProductQuantity(productsInBasket, productId, &#39;increase&#39;);<br>};<br><br>export const decreaseProductQuantityInBasket = (<br>  productsInBasket: Array&lt;ProductInBasket&gt;,<br>  productId: number,<br>) =&gt; {<br>  return updateProductQuantity(productsInBasket, productId, &#39;decrease&#39;);<br>};<br><br>export interface ProductStore {<br>  productsInBasket: Array&lt;ProductInBasket&gt;;<br>  actions: {<br>    addProductToBasket: (val: Product) =&gt; void;<br>    removeProductFromBasket: (productId: number) =&gt; void;<br>    increaseProductQuantityInBasket: (productId: number) =&gt; void;<br>    decreaseProductQuantityInBasket: (productId: number) =&gt; void;<br>    resetAllProductsInBasket: () =&gt; void;<br>  };<br>}<br><br>export const useProductStore = create&lt;ProductStore&gt;((set, get) =&gt; ({<br>  productsInBasket: [],<br>  actions: {<br>    addProductToBasket: product =&gt;<br>      set({<br>        productsInBasket: [<br>          ...get().productsInBasket,<br>          {product: product, quantity: 1},<br>        ],<br>      }),<br>    removeProductFromBasket: productId =&gt;<br>      set({<br>        productsInBasket: [<br>          ...get().productsInBasket.filter(<br>            productInBasket =&gt; productInBasket.product.id !== productId,<br>          ),<br>        ],<br>      }),<br>    increaseProductQuantityInBasket: productId =&gt; {<br>      set({<br>        productsInBasket: increaseProductQuantityInBasket(<br>          get().productsInBasket,<br>          productId,<br>        ),<br>      });<br>    },<br>    resetAllProductsInBasket: () =&gt; set({productsInBasket: []}),<br>    decreaseProductQuantityInBasket: productId =&gt; {<br>      set({<br>        productsInBasket: decreaseProductQuantityInBasket(<br>          get().productsInBasket,<br>          productId,<br>        ),<br>      });<br>    },<br>  },<br>}));<br><br>export const useProductActions = () =&gt; useProductStore(state =&gt; state.actions);<br><br>export const useProductsInBasket = () =&gt;<br>  useProductStore(state =&gt; state.productsInBasket, shallow);<br>export const useProductsInBasketCount = () =&gt;<br>  useProductStore(state =&gt; state.productsInBasket.length);<br>export const useProductInBasketQuantityById = (productId: number | undefined) =&gt;<br>  useProductStore(<br>    state =&gt;<br>      state.productsInBasket.find(<br>        productInBasket =&gt; productInBasket.product.id === productId,<br>      )?.quantity,<br>  );</pre><p>The first part of the code defines three functions, updateProductQuantity, increaseProductQuantityInBasket, and decreaseProductQuantityInBasket, which are helper methods for updating the quantity of a product in the basket. updateProductQuantity function takes an array of objects which corresponds to productsInBasket, a product ID, and an update type (increase or decrease) as inputs, and return a new array productsInBasket with the updated quantity for the given product.</p><p>The ProductStore interface defines the schema for the product store. It contains two properties:</p><ol><li>productsInBasket is an array of ProductInBasketobjects representing the products in the basket.</li><li>actions is an object containing functions for managing the products in the basket, including adding a product, removing a product, increasing/decreasing its quantity, and resetting the basket.</li></ol><p>The useProductStore hook is created using the create function from Zustand. It returns the product store with its state and actions.</p><p>The remaining hooks, useProductActions, useProductsInBasket, useProductsInBasketCount, and useProductInBasketQuantityById, are selectors derived from the useProductStore hook. They allow access to specific parts of the product store, such as the actions or the count of favorited products.</p><p>On the other hand, worth to mention that we used shallowfrom zustand in useProductsInBasket. It&#39;s because the array of objects that will be returned from useProductsInBasket will cause a rerender as they are not being <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive"><em>primitive types</em></a>, thus <a href="https://github.com/pmndrs/zustand#selecting-multiple-state-slices">we simply tell zustand that we want the object to be diffed shallowly by passing the </a><a href="https://github.com/pmndrs/zustand#selecting-multiple-state-slices">shallow equality function.</a></p><h4>1.8 — Installing necessary packages for testing</h4><p>Now, we can move on to the part that we more care about, testing. We will be using the packages below:</p><ul><li><a href="https://jestjs.io/">jest (29.4.1)</a></li><li><a href="https://github.com/kulshekhar/ts-jest">ts-jest (29.0.5)</a></li><li><a href="https://react-hooks-testing-library.com/">@testing-library/react-hooks (8.0.1)</a></li><li><a href="https://callstack.github.io/react-native-testing-library/">@testing-library/react-native (11.5.1)</a></li><li><a href="https://mswjs.io/">Mock service worker aka MSW<em>(1.0.0)</em></a></li></ul><p>For the purpose of brevity and to avoid elongating the article, we will omit some processes of configuring the testing environment such as jest.config.js and ts-jest .</p><p>Feel free to take a look at how we did end up setting up the test environment by using the complete source code link that is available at the end of the article.</p><h4>1.9— Mocking API data with MSW</h4><p>In order to effectively test our app with react-query, we need to mock our API. To accomplish this, we will utilize the mock service worker (MSW).</p><pre>import {rest} from &#39;msw&#39;;<br>import {setupServer} from &#39;msw/node&#39;;<br>import {BASE_URL} from &#39;../../src/api/axios.instance&#39;;<br>import {<br>  GET_ALL_PRODUCTS_MOCK_RESPONSE,<br>  GET_PRODUCT_BY_ID_MOCK_RESPONSE,<br>} from &#39;./mock-data&#39;;<br><br>const getAllProductsUrl = BASE_URL + &#39;/products&#39;;<br>const getProductByIdUrl = BASE_URL + `/products/:id`;<br><br>const getAllProductsHandler = rest.get(getAllProductsUrl, (_req, res, ctx) =&gt; {<br>  return res(ctx.status(200), ctx.json(GET_ALL_PRODUCTS_MOCK_RESPONSE));<br>});<br><br>const getProductByIdHandler = rest.get(getProductByIdUrl, (_req, res, ctx) =&gt; {<br>  return res(ctx.status(200), ctx.json(GET_PRODUCT_BY_ID_MOCK_RESPONSE));<br>});<br><br>const handlers = [getAllProductsHandler, getProductByIdHandler];<br><br>export const mswServer = setupServer(...handlers);<br><br>const getAllProductsFailedHandler = rest.get(<br>  getAllProductsUrl,<br>  (_req, res, ctx) =&gt; {<br>    return res(ctx.status(500));<br>  },<br>);<br><br>const getProductByIdFailedHandler = rest.get(<br>  getProductByIdUrl,<br>  (_req, res, ctx) =&gt; {<br>    return res(ctx.status(500));<br>  },<br>);<br><br>export const setupGetAllProductsFailedHandler = () =&gt;<br>  mswServer.use(getAllProductsFailedHandler);<br><br>export const setupGetProductByIdFailedHandler = () =&gt;<br>  mswServer.use(getProductByIdFailedHandler);</pre><p>In the code above, we import the necessary modules and set up the MSW handlers. We create two mock endpoints, one for fetching all products and the other for fetching a product by its id, both returning a successful response. To ensure thorough testing, we also create failed handlers for these two endpoints to simulate and test failure scenarios.</p><p>In order to complete the mocking setup above, we need to use mswServer object in our jest.setup.js . We simply will want to initialize mswServer before any test cases, as well as reset handlers after each test case, and in the end, we will shut down it.</p><pre>import &#39;react-native-gesture-handler/jestSetup&#39;;<br>import {mswServer} from &#39;./__mocks__/msw/handlers&#39;;<br><br>jest.useFakeTimers();<br><br>// https://mswjs.io/docs/getting-started/integrate/node#setup<br><br>// Establish API mocking before all tests.<br>beforeAll(() =&gt; mswServer.listen());<br>// Reset any request handlers that we may add during the tests,<br>// so they don&#39;t affect other tests.<br>afterEach(() =&gt; mswServer.resetHandlers());<br>// Clean up after the tests are finished.<br>afterAll(() =&gt; mswServer.close());<br><br>// Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing<br>jest.mock(&#39;react-native/Libraries/Animated/NativeAnimatedHelper&#39;);</pre><p>Now, we mocked our API to be able to use it in the tests. But we still are not complete yet. We do also need to set up testing for zustand <a href="https://docs.pmnd.rs/zustand/guides/testing">using the documentation they have provided.</a> This will allow us to <a href="https://docs.pmnd.rs/zustand/guides/testing">reset state between tests</a> when using zustand in our test cases.</p><h4>1.10 — Configuring zustand for testing</h4><pre>// https://docs.pmnd.rs/zustand/guides/testing#resetting-state-between-tests-in-react-dom<br>const {create: actualCreate} = jest.requireActual(&#39;zustand&#39;); // if using jest<br>import {act} from &#39;@testing-library/react-native&#39;;<br><br>// a variable to hold reset functions for all stores declared in the app<br>const storeResetFns = new Set();<br><br>// when creating a store, we get its initial state, create a reset function and add it in the set<br>export const create = createState =&gt; {<br>  const store = actualCreate(createState);<br>  const initialState = store.getState();<br>  storeResetFns.add(() =&gt; store.setState(initialState, true));<br>  return store;<br>};<br><br>// Reset all stores after each test run<br>beforeEach(() =&gt; {<br>  act(() =&gt; storeResetFns.forEach(resetFn =&gt; resetFn()));<br>});</pre><p>The crucial thing is here to put the file above in the correct directory depending on our testing environment. Since we use jest, we should place this file to the __mocks__/zustand.js <a href="https://docs.pmnd.rs/zustand/guides/testing">as described in the documentation</a>.</p><p>You might be already feeling overwhelmed dealing with setting up the (testing) environment, nevertheless, I needed to cover them regardless, as they are the skeleton of our environment.</p><p>That said, let’s jump right into the section in which we create our screen for displaying the products.</p><h4>2 — Product list screen overview</h4><p>As we mentioned before, we will have a screen for displaying products. Let’s see the full code of product list screen below:</p><pre>import {DefaultTheme} from &#39;@react-navigation/native&#39;;<br>import * as React from &#39;react&#39;;<br>import {<br>  FlatList,<br>  ListRenderItemInfo,<br>  RefreshControl,<br>  StyleSheet,<br>  Text,<br>  View,<br>} from &#39;react-native&#39;;<br>import {SafeAreaView} from &#39;react-native-safe-area-context&#39;;<br>import {Product, useGetAllProducts} from &#39;../api/product&#39;;<br>import ProductListCard from &#39;../components/product-list-card&#39;;<br>import ScreenLoading from &#39;../components/screen-loading&#39;;<br>import Spacing from &#39;../components/spacing&#39;;<br>import useRefreshByUser from &#39;../hooks/useRefreshByUser&#39;;<br>import {RouteNames} from &#39;../navigation/route-names&#39;;<br>import {ProductListScreenProps} from &#39;../navigation/types&#39;;<br>import {useProductActions, useProductsInBasket} from &#39;../store/product&#39;;<br>import {COMMON_STYLES} from &#39;../theme/common-styles&#39;;<br><br>type Props = ProductListScreenProps;<br><br>const ProductListScreen: React.FC&lt;Props&gt; = ({navigation}) =&gt; {<br>  const {data, isLoading, refetch, isError, isSuccess} = useGetAllProducts();<br><br>  const {isRefetchingByUser, refetchByUser} = useRefreshByUser(refetch);<br><br>  const {addProductToBasket, removeProductFromBasket} = useProductActions();<br>  const productsInBasket = useProductsInBasket();<br><br>  const onAddToBasketPress = React.useCallback(<br>    (product: Product) =&gt; () =&gt; {<br>      if (<br>        productsInBasket.find(<br>          productInBasket =&gt; productInBasket.product.id === product.id,<br>        )<br>      ) {<br>        removeProductFromBasket(product.id);<br>      } else {<br>        addProductToBasket(product);<br>      }<br>    },<br>    [addProductToBasket, productsInBasket, removeProductFromBasket],<br>  );<br><br>  const onProductCardPress = React.useCallback(<br>    (productId: number) =&gt; () =&gt; {<br>      navigation.navigate(RouteNames.productDetail, {id: productId});<br>    },<br>    [navigation],<br>  );<br><br>  const renderItemSeparator = () =&gt; (<br>    &lt;Spacing<br>      backgroundColor={DefaultTheme.colors.background}<br>      height={COMMON_STYLES.screenPadding}<br>    /&gt;<br>  );<br><br>  const getKeyExtractor = (item: Product) =&gt; item.id.toString();<br><br>  const renderItem = ({item: product}: ListRenderItemInfo&lt;Product&gt;) =&gt; {<br>    return (<br>      &lt;ProductListCard<br>        {...product}<br>        testID={`product-list-card-${product.id}`}<br>        basketButtonTestID={`basket-button-${product.id}`}<br>        isInBasket={<br>          typeof productsInBasket.find(<br>            productInBasket =&gt; productInBasket.product.id === product.id,<br>          ) !== &#39;undefined&#39;<br>        }<br>        onAddToBasketPress={onAddToBasketPress(product)}<br>        onPress={onProductCardPress(product.id)}<br>      /&gt;<br>    );<br>  };<br><br>  if (isLoading) {<br>    return &lt;ScreenLoading /&gt;;<br>  }<br><br>  return (<br>    &lt;SafeAreaView style={COMMON_STYLES.flex} edges={[&#39;bottom&#39;]}&gt;<br>      {isError &amp;&amp; (<br>        &lt;View style={COMMON_STYLES.flexCenter}&gt;<br>          &lt;Text&gt;An error occurred&lt;/Text&gt;<br>        &lt;/View&gt;<br>      )}<br><br>      {isSuccess &amp;&amp; (<br>        &lt;FlatList&lt;Product&gt;<br>          data={data}<br>          testID=&quot;product-list-flat-list&quot;<br>          refreshControl={<br>            &lt;RefreshControl<br>              refreshing={isRefetchingByUser}<br>              onRefresh={refetchByUser}<br>            /&gt;<br>          }<br>          renderItem={renderItem}<br>          numColumns={2}<br>          ItemSeparatorComponent={renderItemSeparator}<br>          columnWrapperStyle={styles.columnWrapper}<br>          contentContainerStyle={styles.contentContainerStyle}<br>          showsVerticalScrollIndicator={false}<br>          keyExtractor={getKeyExtractor}<br>          style={COMMON_STYLES.flex}<br>        /&gt;<br>      )}<br>    &lt;/SafeAreaView&gt;<br>  );<br>};<br><br>export default ProductListScreen;<br><br>const styles = StyleSheet.create({<br>  contentContainerStyle: {<br>    flexGrow: 1,<br>    padding: COMMON_STYLES.screenPadding,<br>  },<br>  columnWrapper: {<br>    justifyContent: &#39;space-between&#39;,<br>  },<br>});</pre><p>This screen is responsible for the followings:</p><ul><li>Displaying products with the custom react query hook, useGetAllProducts , which we created in <a href="#3b33"><strong><em>1.4 — Fetching products using react-query</em></strong></a> section.</li><li>Allowing users to add or remove products from their basket using the useProductActions custom zustand hook which again we have covered in <a href="#9788"><strong><em>1.7 — Here comes zustand, managing products in the basket</em></strong></a> section.</li><li>Refetching products using pull-to-refresh.</li><li>Updating the quantity text displayed in the header right basket icon.</li></ul><p>Below is the demonstration of product list screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*7wGmDzti0z-d0oPFkKkhCw.gif" /></figure><h4>2.1 — Testing product list screen</h4><p>In this section, we will be conducting testing on product list screen. The initial test cases that will be carried out are as follows:</p><ul><li>Initially, the loading indicator should be displayed, even though we mock the data. The isLoading boolean flag in react-query will still be set to truefor a short period of time. After the data is fetched, isLoading will be false, and the loader will not be displayed.</li><li>The product list should be displayed accurately after the data has been fetched. The testID prop of the ProductListCardcomponent will be utilized to verify this case.</li><li>In the event of a failed query to get all products, the screen should display an error message. We will be utilizing the setupGetAllProductsFailedHandler helper that was created in <a href="#13ff"><strong><em>1.9 — Mocking API data with MSW</em></strong></a> section.</li></ul><h4>2.1.1 —Test case: Initially, it should display loading indicator</h4><pre>import {renderHook} from &#39;@testing-library/react-hooks&#39;;<br>import {render, screen} from &#39;@testing-library/react-native&#39;;<br>import React from &#39;react&#39;;<br>import {useGetAllProducts} from &#39;../../api/product&#39;;<br>import {createReactQueryWrapper} from &#39;../../utils/testing&#39;;<br>import ProductListScreen from &#39;../product-list&#39;;<br><br>const navigateMock = jest.fn();<br>const navigation = {navigate: navigateMock} as any;<br>const route = jest.fn() as any;<br><br>const component = &lt;ProductListScreen navigation={navigation} route={route} /&gt;;<br><br>describe(&#39;Product list screen&#39;, () =&gt; {<br>  it(&#39;should display loading indicator initially&#39;, async () =&gt; {<br>    // We render the component and expect to see a loading indicator<br>    render(component, {wrapper: createReactQueryWrapper});<br>    expect(screen.queryByTestId(`screen-loader`)).toBeTruthy();<br><br>    // We render the product list using useGetAllProducts hook and wait until the products are loaded<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // We expect the loading indicator to disappear after the products are loaded<br>    expect(screen.queryByTestId(`screen-loader`)).not.toBeTruthy();<br>  });<br>});</pre><p>At the top of the file, we’ve imported the necessary modules in order to run our tests. And then we created a variable called as component to store our product list screen, so that we can reuse this variable throughout our test cases. Furthermore, since it is a screen, and we declared screen props in section <a href="#a241"><strong><em>2 — Product list screen overview</em></strong></a>, and in<strong><em> line 22</em></strong>, we also need to provide the required screen props, navigationand route. We will come back in upcoming test cases on why we destructed the navigation object in the above.</p><p><strong>A short review of terminology we need to take care of in order to understand test cases:</strong></p><ul><li><a href="https://callstack.github.io/react-native-testing-library/docs/api#render">render</a>: Deeply renders given React element and returns helpers to query the output components structure.</li><li><a href="https://callstack.github.io/react-native-testing-library/docs/api#screen">screen</a>: Hold the value of latest render call for easier access to query and other functions returned by <a href="https://callstack.github.io/react-native-testing-library/docs/api#render">render</a>.</li><li><a href="https://react-hooks-testing-library.com/reference/api#renderhook">renderHook</a> : Renders a test component that will call the provided callback, including any hooks it calls, every time it renders.</li></ul><blockquote>Since the primary objective of this article is to provide guidance on how to conduct testing rather than an introduction to testing libraries, and their functions, we will skip diving into deep detail about them. We will have enough examples to see their usage anyway throughout the article.</blockquote><p>The test case above checks if a screen loader component is displayed initially on the screen. The render function renders the ProductListScreen component wrapped in the createReactQueryWrapper function, which is a simple utility function used for creating <a href="https://tanstack.com/query/v4/docs/react/reference/QueryClientProvider">QueryClientProvider</a> . The screen.queryByTestId() function checks if the screen loader is displayed on the screen.</p><p>The renderHook function is used to test the useGetAllProducts hook, which is used in the ProductListScreen component to fetch the products data. The wrapper option is passed to the renderHook function to wrap the useGetAllProducts hook in the createReactQueryWrapper function. The result variable contains the value returned by the useGetAllProducts hook. Meanwhile, the waitFor function waits until the isSuccess property of the result object is true, which means that the products data has been successfully fetched.</p><p>The second part checks if the screen loader component is no longer displayed after the product data has been successfully fetched.</p><blockquote>The reason we used queryByTestId instead of getByTestId is because we know that screen loader component <strong>will not be visible</strong> after data has been fetched, thus using getByTestId would throw an error.</blockquote><p>The error we would be facing could be the following in case of using getByTestId:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3eXZ10vsIAEedjFSUBQ4w.png" /></figure><h4>2.1.2 — Test case: It should display product list data correctly</h4><pre>import {renderHook} from &#39;@testing-library/react-hooks&#39;;<br>import {render, screen} from &#39;@testing-library/react-native&#39;;<br>import React from &#39;react&#39;;<br>import {useGetAllProducts} from &#39;../../api/product&#39;;<br>import {createReactQueryWrapper} from &#39;../../utils/testing&#39;;<br>import ProductListScreen from &#39;../product-list&#39;;<br><br>const navigateMock = jest.fn();<br>const navigation = {navigate: navigateMock} as any;<br>const route = jest.fn() as any;<br><br>const component = &lt;ProductListScreen navigation={navigation} route={route} /&gt;;<br><br>describe(&#39;Product list screen&#39;, () =&gt; {<br>  it(&#39;should display product list data correctly&#39;, async () =&gt; {<br>    // Render the component and wait for it to load<br>    render(component, {wrapper: createReactQueryWrapper});<br><br>    // Check that no product card is rendered before fetching data<br>    expect(screen.queryByTestId(`product-list-card-1`)).not.toBeTruthy();<br><br>    // Fetch the product data<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // Wait for the data to be fetched successfully<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // Check that each product card is rendered for each product in the data<br>    for (const {id} of result.current.data!) {<br>      expect(screen.queryByTestId(`product-list-card-${id}`)).toBeTruthy();<br>    }<br>  });<br>});</pre><p>This test code tests whether the product list screen displays the fetched product data correctly.</p><p>This time again we wait for data to be fetched successfully, then we are ensuring product list data is displayed correctly by looping through the fetched data and expecting that a product list card with the testID of product-list-card-${id} exists for each product in the data. The id property is dynamically generated based on the product ID. If the test fails, it means that the product list items are not displaying the product data correctly.</p><p>Notice how we were using the renderItem function in order to render list items below. We loop through product.id and combine with the string product-list-card to generate a dynamic testID for the ProductListCard component. In this way, we will be able to test all of the products along with their respective testID prop.</p><pre>const renderItem = ({item: product}: ListRenderItemInfo&lt;Product&gt;) =&gt; {<br>    return (<br>      &lt;ProductListCard<br>        {...product}<br>        testID={`product-list-card-${product.id}`}<br>        basketButtonTestID={`basket-button-${product.id}`}<br>        isInBasket={<br>          typeof productsInBasket.find(<br>            productInBasket =&gt; productInBasket.product.id === product.id,<br>          ) !== &#39;undefined&#39;<br>        }<br>        onAddToBasketPress={onAddToBasketPress(product)}<br>        onPress={onProductCardPress(product.id)}<br>      /&gt;<br>    );<br>  };</pre><h4>2.1.3— Test case: It should display error text in case get all products query fails</h4><p>In this test case, we are testing the scenario where the API call to fetch all products fails.</p><pre>import {renderHook} from &#39;@testing-library/react-hooks&#39;;<br>import {render, screen} from &#39;@testing-library/react-native&#39;;<br>import React from &#39;react&#39;;<br>import {setupGetAllProductsFailedHandler} from &#39;../../../__mocks__/msw/handlers&#39;;<br>import {useGetAllProducts} from &#39;../../api/product&#39;;<br>import {createReactQueryWrapper} from &#39;../../utils/testing&#39;;<br>import ProductListScreen from &#39;../product-list&#39;;<br><br>const navigateMock = jest.fn();<br>const navigation = {navigate: navigateMock} as any;<br>const route = jest.fn() as any;<br><br>const component = &lt;ProductListScreen navigation={navigation} route={route} /&gt;;<br><br>describe(&#39;Product list screen&#39;, () =&gt; {<br>  it(&#39;should display error text in case get all products query fails&#39;, async () =&gt; {<br>    // Set up the mock handler for GET requests to the /products endpoint that returns an error response<br>    setupGetAllProductsFailedHandler();<br><br>    // Render the ProductListScreen component wrapped in the React Query wrapper<br>    render(component, {wrapper: createReactQueryWrapper});<br><br>    // Set up a mock React hook that calls the useGetAllProducts hook from the API module<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // Wait for the useGetAllProducts hook to throw an error<br>    await waitFor(() =&gt; result.current.isError);<br><br>    // Assert that the &quot;An error occurred&quot; text is displayed on the screen<br>    expect(screen.getByText(`An error occurred`)).toBeTruthy();<br>  });<br>});</pre><p>To simulate API failure, we use the setupGetAllProductsFailedHandler function from the mock server worker (msw), which we implement <a href="#13ff"><strong><em>1.9 — Mocking API data with MSW</em></strong></a> section in line 38. We then render the ProductListScreencomponent using the render function, and invoke the useGetAllProducts hook which fetches the data using the renderHook function.</p><p>We use the waitFor function from @testing-library/react-hooks to wait for the isError property of the result.current object to become true. This ensures that the hook has completed executing and the API call has failed. Finally, we assert that the error message “An error occurred” <a href="#a241"><em>(which you can double check by taking a look at the source code of the product list screen)</em></a> will be displayed on the screen by checking if the text is present using the getByText function from @testing-library/react-native.</p><h4>2.1.4 — Test case: It should call navigation action on pressing the first product item</h4><p>We will test the following code snippet which is actually extracted from our product list screen. This code is responsible for handling user press action to any of the product list card in the list.</p><pre>const onProductCardPress = React.useCallback(<br>    (productId: number) =&gt; () =&gt; {<br>      navigation.navigate(RouteNames.productDetail, {id: productId});<br>    },<br>    [navigation],<br>  );<br><br><br> const renderItem = ({item: product}: ListRenderItemInfo&lt;Product&gt;) =&gt; {<br>    return (<br>      &lt;ProductListCard<br>        {...product}<br>        testID={`product-list-card-${product.id}`}<br>        basketButtonTestID={`basket-button-${product.id}`}<br>        isInBasket={<br>          typeof productsInBasket.find(<br>            productInBasket =&gt; productInBasket.product.id === product.id,<br>          ) !== &#39;undefined&#39;<br>        }<br>        onAddToBasketPress={onAddToBasketPress(product)}<br>        onPress={onProductCardPress(product.id)}<br>      /&gt;<br>    );<br>  };</pre><p>Let’s see below how we can approach testing it:</p><pre>import {renderHook} from &#39;@testing-library/react-hooks&#39;;<br>import {fireEvent, render, screen} from &#39;@testing-library/react-native&#39;;<br>import React from &#39;react&#39;;<br>import {useGetAllProducts} from &#39;../../api/product&#39;;<br>import {RouteNames} from &#39;../../navigation/route-names&#39;;<br>import {createReactQueryWrapper} from &#39;../../utils/testing&#39;;<br>import ProductListScreen from &#39;../product-list&#39;;<br><br>const navigateMock = jest.fn();<br>const navigation = {navigate: navigateMock} as any;<br>const route = jest.fn() as any;<br><br>const component = &lt;ProductListScreen navigation={navigation} route={route} /&gt;;<br><br>describe(&#39;Product list screen&#39;, () =&gt; {<br>  it(&#39;should call navigation action on pressing the first product item&#39;, async () =&gt; {<br>    // render ProductListScreen component with createReactQueryWrapper as a wrapper<br>    render(component, {wrapper: createReactQueryWrapper});<br><br>    // render hook for useGetAllProducts with createReactQueryWrapper as a wrapper<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // wait for useGetAllProducts to succeed<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // find first product item and simulate a press event on it<br>    const firstProductItem = screen.getByTestId(`product-list-card-1`);<br>    fireEvent.press(firstProductItem);<br><br>    // assert that navigation action was called with correct route name and params<br>    expect(navigateMock).toHaveBeenCalledWith(RouteNames.productDetail, {<br>      id: 1,<br>    });<br>  });<br>});</pre><p>In this test code snippet, we are testing whether the navigation action is called when a product item is pressed. First, we render the ProductListScreen component and wait for data to be fetched successfully just like in previous test cases. Afterward, we retrieve the first product item from the list and simulate a press event on it using fireEvent.press. Finally, we expect that the navigate function of the navigation object has been called with the expected RouteName and productId parameters.</p><h4>2.1.5 — Test case: It should add/remove product item correctly on pressing product item’s basket icon</h4><p>The test case below is testing the scenario where the user adds and removes a product from the basket by pressing the basket icon on the product card on the Product List screen.</p><pre>import {NavigationContainer} from &#39;@react-navigation/native&#39;;<br>import {renderHook} from &#39;@testing-library/react-hooks&#39;;<br>import {fireEvent, render, screen} from &#39;@testing-library/react-native&#39;;<br>import React from &#39;react&#39;;<br>import {useGetAllProducts} from &#39;../../api/product&#39;;<br>import ProductStack from &#39;../../navigation/product-stack&#39;;<br>import {useProductStore} from &#39;../../store/product&#39;;<br>import {createReactQueryWrapper} from &#39;../../utils/testing&#39;;<br><br>// We render the whole app stack instead of rendering just the screen<br>// because we need access to the react-navigation&#39;s header, which wouldn&#39;t<br>// be possible if we just rendered the screen.<br>const rootAppComponent = (<br>  &lt;NavigationContainer&gt;<br>    &lt;ProductStack /&gt;<br>  &lt;/NavigationContainer&gt;<br>);<br><br>describe(&#39;Product list screen&#39;, () =&gt; {<br>  it(&#39;should add/remove product item correctly on pressing product items basket icon&#39;, async () =&gt; {<br>    // We render the entire app stack and use the createReactQueryWrapper as a<br>    // wrapper for the render function to set up the React Query Provider.<br>    render(rootAppComponent, {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // We use the renderHook function to invoke the useGetAllProducts hook which<br>    // fetches the data.<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // We use the renderHook function to get access to the useProductStore hook<br>    // which we will use to check that the products in the basket were added/removed correctly.<br>    const {result: productStore} = renderHook(() =&gt; useProductStore(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // We wait for the useGetAllProducts hook to complete fetching the data before proceeding<br>    // with the test.<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // We get the basket button for the first product item using the getByTestId function.<br>    const firstProductItemBasketButton = screen.getByTestId(`basket-button-1`);<br><br>    // We click the basket button for the first product item.<br>    fireEvent.press(firstProductItemBasketButton);<br><br>    // We check that the basket icon quantity text is present using the getByTestId function.<br>    expect(screen.getByTestId(&#39;basket-icon-quantity-text-1&#39;)).toBeTruthy();<br><br>    // We check that the products in the basket have been added correctly using the productStore.<br>    expect(productStore.current.productsInBasket).toHaveLength(1);<br>    expect(productStore.current.productsInBasket[0].quantity).toBe(1);<br>    expect(productStore.current.productsInBasket[0].product).toMatchObject(<br>      result.current.data![0],<br>    );<br><br>    // We click the basket button for the first product item again to remove it from the basket.<br>    fireEvent.press(firstProductItemBasketButton);<br><br>    // We check that the basket icon quantity text is not present.<br>    expect(<br>      screen.queryByTestId(&#39;basket-icon-quantity-text-1&#39;),<br>    ).not.toBeTruthy();<br><br>    // We check that the products in the basket have been removed correctly using the productStore.<br>    expect(productStore.current.productsInBasket).toHaveLength(0);<br>  });<br>});</pre><p>In order to test the functionality of the basket icon on the header, we need to render the entire ProductStack in addition to the ProductListScreen. This is because we need to access the header of the Product List screen to get the basket icon by its test ID. This requires us to have the entire ProductStackrendered, along with the NavigationContainer .</p><p>After we are done with fetching products successfully, it uses fireEvent.press to simulate pressing the basket icon on the first product item, which adds the product to the basket. We then check that the basket icon displays the correct quantity, and that the product is added to the productsInBasket array in the product store with the correct quantity and product object.</p><p>After that, we do simulate pressing the basket icon again to remove the product from the basket, and check that the basket icon no longer displays the quantity, and that the productsInBasket array in the product store is empty.</p><p>In summary, this test case is testing the functionality of adding and removing a product from the basket as well as adjusting their quantities by pressing the basket icon on the product card on the Product List screen, and confirms that the product store correctly manages the products and their quantities in the basket.</p><h4>2.1.6 — Product list screen complete test flow</h4><p>The complete test flow of the product list screen is as follows:</p><pre>import {NavigationContainer} from &#39;@react-navigation/native&#39;;<br>import {renderHook} from &#39;@testing-library/react-hooks&#39;;<br>import {fireEvent, render, screen} from &#39;@testing-library/react-native&#39;;<br>import React from &#39;react&#39;;<br>import {setupGetAllProductsFailedHandler} from &#39;../../../__mocks__/msw/handlers&#39;;<br>import {useGetAllProducts} from &#39;../../api/product&#39;;<br>import ProductStack from &#39;../../navigation/product-stack&#39;;<br>import {RouteNames} from &#39;../../navigation/route-names&#39;;<br>import {useProductStore} from &#39;../../store/product&#39;;<br>import {createReactQueryWrapper} from &#39;../../utils/testing&#39;;<br>import ProductListScreen from &#39;../product-list&#39;;<br><br>// We render the whole app stack instead of rendering just the screen<br>// because we need access to the react-navigation&#39;s header, which wouldn&#39;t<br>// be possible if we just rendered the screen.<br>const rootAppComponent = (<br>  &lt;NavigationContainer&gt;<br>    &lt;ProductStack /&gt;<br>  &lt;/NavigationContainer&gt;<br>);<br>const navigateMock = jest.fn();<br>const navigation = {navigate: navigateMock} as any;<br>const route = jest.fn() as any;<br><br>const component = &lt;ProductListScreen navigation={navigation} route={route} /&gt;;<br><br>describe(&#39;Product list screen&#39;, () =&gt; {<br>  it(&#39;should display loading indicator initially&#39;, async () =&gt; {<br>    // We render the component and expect to see a loading indicator<br>    render(component, {wrapper: createReactQueryWrapper});<br>    expect(screen.queryByTestId(`screen-loader`)).toBeTruthy();<br><br>    // We render the product list using useGetAllProducts hook and wait until the products are loaded<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // We expect the loading indicator to disappear after the products are loaded<br>    expect(screen.queryByTestId(`screen-loader`)).not.toBeTruthy();<br>  });<br><br>  it(&#39;should display product list data correctly&#39;, async () =&gt; {<br>    // Render the component and wait for it to load<br>    render(component, {wrapper: createReactQueryWrapper});<br><br>    // Check that no product card is rendered before fetching data<br>    expect(screen.queryByTestId(`product-list-card-1`)).not.toBeTruthy();<br><br>    // Fetch the product data<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // Wait for the data to be fetched successfully<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // Check that each product card is rendered for each product in the data<br>    for (const {id} of result.current.data!) {<br>      expect(screen.queryByTestId(`product-list-card-${id}`)).toBeTruthy();<br>    }<br>  });<br><br>  it(&#39;should display error text in case get all products query fails&#39;, async () =&gt; {<br>    // Set up the mock handler for GET requests to the /products endpoint that returns an error response<br>    setupGetAllProductsFailedHandler();<br><br>    // Render the ProductListScreen component wrapped in the React Query wrapper<br>    render(component, {wrapper: createReactQueryWrapper});<br><br>    // Set up a mock React hook that calls the useGetAllProducts hook from the API module<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // Wait for the useGetAllProducts hook to throw an error<br>    await waitFor(() =&gt; result.current.isError);<br><br>    // Assert that the &quot;An error occurred&quot; text is displayed on the screen<br>    expect(screen.getByText(`An error occurred`)).toBeTruthy();<br>  });<br><br>  it(&#39;should call navigation action on pressing the first product item&#39;, async () =&gt; {<br>    // Render the ProductListScreen component along with react-query wrapper<br>    render(component, {wrapper: createReactQueryWrapper});<br><br>    // Render the useGetAllProducts hook with react-query wrapper to fetch data<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // Wait for the data to be fetched<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // Find the first product card in the list and simulate a press event on it<br>    const firstProductItem = screen.getByTestId(`product-list-card-1`);<br>    fireEvent.press(firstProductItem);<br><br>    // Expect that the navigation function is called with the correct route name and params<br>    expect(navigateMock).toHaveBeenCalledWith(RouteNames.productDetail, {<br>      id: 1,<br>    });<br>  });<br><br>  it(&#39;should add/remove product item correctly on pressing product items basket icon&#39;, async () =&gt; {<br>    // We render the entire app stack and use the createReactQueryWrapper as a<br>    // wrapper for the render function to set up the React Query Provider.<br>    render(rootAppComponent, {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // We use the renderHook function to invoke the useGetAllProducts hook which<br>    // fetches the data.<br>    const {result, waitFor} = renderHook(() =&gt; useGetAllProducts(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // We use the renderHook function to get access to the useProductStore hook<br>    // which we will use to check that the products in the basket were added/removed correctly.<br>    const {result: productStore} = renderHook(() =&gt; useProductStore(), {<br>      wrapper: createReactQueryWrapper,<br>    });<br><br>    // We wait for the useGetAllProducts hook to complete fetching the data before proceeding<br>    // with the test.<br>    await waitFor(() =&gt; result.current.isSuccess);<br><br>    // We get the basket button for the first product item using the getByTestId function.<br>    const firstProductItemBasketButton = screen.getByTestId(`basket-button-1`);<br><br>    // We click the basket button for the first product item.<br>    fireEvent.press(firstProductItemBasketButton);<br><br>    // We check that the basket icon quantity text is present using the getByTestId function.<br>    expect(screen.getByTestId(&#39;basket-icon-quantity-text-1&#39;)).toBeTruthy();<br><br>    // We check that the products in the basket have been added correctly using the productStore.<br>    expect(productStore.current.productsInBasket).toHaveLength(1);<br>    expect(productStore.current.productsInBasket[0].quantity).toBe(1);<br>    expect(productStore.current.productsInBasket[0].product).toMatchObject(<br>      result.current.data![0],<br>    );<br><br>    // We click the basket button for the first product item again to remove it from the basket.<br>    fireEvent.press(firstProductItemBasketButton);<br><br>    // We check that the basket icon quantity text is not present.<br>    expect(<br>      screen.queryByTestId(&#39;basket-icon-quantity-text-1&#39;),<br>    ).not.toBeTruthy();<br><br>    // We check that the products in the basket have been removed correctly using the productStore.<br>    expect(productStore.current.productsInBasket).toHaveLength(0);<br>  });<br>});</pre><h4>Wrapping up</h4><p>To conclude, this article has explored effective testing strategies for React Native applications that use React-Query and Zustand libraries which are pretty popular these days in any React/React Native applications. By using a simple store app as an example and providing comprehensive and detailed examples, we have covered the testing process and how to ensure code quality through the implementation of tests. Feel free to take a look at the full source code using the link below. Have a good day!</p><p><a href="https://github.com/tarikpnr/react-native-testing"><strong>Full source code link</strong></a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d957c2a40b73" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/testing-react-native-with-react-query-and-zustand-d957c2a40b73">Testing React Native with React-Query and Zustand</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using React Native Async Storage]]></title>
            <link>https://levelup.gitconnected.com/stop-using-react-native-async-storage-fdbcc05a6de3?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdbcc05a6de3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 14:37:09 GMT</pubDate>
            <atom:updated>2023-07-03T16:04:03.167Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Comparison of React Native MMKV and React Native Async Storage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f5FAc401uPezI6pa" /><figcaption>Photo by <a href="https://unsplash.com/@moneyphotos?utm_source=medium&amp;utm_medium=referral">regularguy.eth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For quite some time, React Native Async Storage has been the go-to option for storing data in React Native applications. However, the introduction of React-Native MMKV presents developers with a more efficient and advanced choice.</p><p>MMKV, originally designed as an efficient, small, and user-friendly mobile key-value storage framework for the WeChat app.</p><p>It brings its fast, direct bindings to the native C++ library to the React Native platform through a simple JavaScript API. React-Native MMKV is now a prominent option for data storage in React Native applications. One of the key advantages of React-Native MMKV is its performance. With everything written in C++, <strong><em>it is ~30x faster than AsyncStorage</em></strong>. Furthermore, it also provides encryption support, making it a secure storage solution for your app. The use of JSI instead of the “old” Bridge further enhances its speed and efficiency.</p><h4>Benchmark</h4><p><a href="https://github.com/mrousavy/react-native-mmkv#benchmark"><em>MMKV vs other storage libraries: Reading a value from Storage 1000 times.<br>Measured in milliseconds on an iPhone 11 Pro, lower is better.</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*v6sX7AfLoqGWl6nK6XoneA.png" /><figcaption><a href="https://github.com/mrousavy/react-native-mmkv#benchmark">https://github.com/mrousavy/react-native-mmkv#benchmark</a></figcaption></figure><h4><strong>No Async/Await</strong></h4><p>React-Native MMKV also offers fully synchronous calls, making it easy to use without async/await or Promises. This is in contrast to AsyncStorage, which requires asynchronous behavior. With react-native-mmkv, you can easily store and retrieve data using simple getters and setters. Let’s see how we can initialize our storage using react-native-mmkv:</p><pre>import { MMKV } from &#39;react-native-mmkv&#39;<br><br>export const appStorage = new MMKV({<br>  id: &#39;my-app-storage&#39;,<br>})</pre><p>Retrieving data from storage is also just as straightforward, as shown below:</p><pre>// set a new key/value pair using react-native-mmkv<br>appStorage.set(&#39;username&#39;, &#39;John&#39;)<br>const username = appStorage.getString(&#39;username&#39;)<br><br>// below is how you would do using react-native-async-storage<br>await AsyncStorage.setItem(&#39;username&#39;, &#39;John&#39;)<br>const username =  await AsyncStorage.getItem(&#39;username&#39;)</pre><p>React-Native MMKV also provides support for object storage, making it easy to store complex data structures. This is shown in the following code:</p><pre>// Objects <br><br>// using react-native-mmkv<br><br>const user = {<br>  username: &#39;John&#39;,<br>  role: &#39;Admin&#39;<br>}<br><br>appStorage.set(&#39;user&#39;, JSON.stringify(user))<br><br>const jsonUser = appStorage.getString(&#39;user&#39;) <br>const userObject = JSON.parse(jsonUser)<br><br>// using react-native-async-storage<br><br>await AsyncStorage.setItem(&#39;user&#39;, JSON.stringify(user))<br>const jsonUser = await AsyncStorage.getItem(&#39;user&#39;)<br>const userObject = JSON.parse(jsonUser)</pre><p>Removing items from storage is just as easy, as demonstrated below:</p><pre>// to remove specific item from the storage in mmkv<br>appStorage.delete(&#39;username&#39;)<br><br>// below is how you would do using react-native-async-storage<br>await AsyncStorage.removeItem(&#39;username&#39;)</pre><h4>Real life example - Zustand middleware-persist and React Native MMKV</h4><p>React-Native MMKV has the ability to integrate with popular state management libraries such as jotai, redux-persist, mobx-persist, and zustand-persist-middleware. This allows developers to leverage the power of MMKV’s efficient, fast, and easy-to-use storage capabilities with their existing state management solutions. The integration results in a seamless and streamlined state management experience, making it easier for developers to manage and persist their application data.</p><pre>import { Appearance } from &quot;react-native&quot;;<br>import { MMKV } from &quot;react-native-mmkv&quot;;<br>import create from &quot;zustand&quot;;<br>import { persist, StateStorage } from &quot;zustand/middleware&quot;;<br><br>type AppPersistStore = {<br>  isDarkTheme: boolean;<br>  setIsDarkTheme: (preference: boolean) =&gt; void;<br>};<br><br>export const appPersistStorage = new MMKV({ id: &quot;app-persist-storage&quot; });<br><br>const zustandMMKVStorage: StateStorage = {<br>  setItem: (name, value) =&gt; {<br>    return appPersistStorage.set(name, value);<br>  },<br>  getItem: (name) =&gt; {<br>    const value = appPersistStorage.getString(name);<br>    return value ?? null;<br>  },<br>  removeItem: (name) =&gt; {<br>    return appPersistStorage.delete(name);<br>  },<br>};<br><br>export const useAppPersistStore = create&lt;<br>  AppPersistStore,<br>  [[&quot;zustand/persist&quot;, AppPersistStore]]<br>&gt;(<br>  persist(<br>    (set, get) =&gt; ({<br>      isDarkTheme: Appearance.getColorScheme() === &quot;dark&quot;,<br>      setIsDarkTheme: (preference) =&gt; set({ isDarkTheme: preference }),<br>    }),<br>    {<br>      name: &quot;app-persist-storage&quot;,<br>      getStorage: () =&gt; zustandMMKVStorage,<br>      serialize: (state) =&gt; JSON.stringify(state),<br>      deserialize: (state) =&gt; JSON.parse(state),<br>    },<br>  ),<br>);</pre><p>The code snippet above demonstrates the use of the zustand-persist-middleware with react-native-mmkv for handling the app&#39;s light/dark theme. The combination of these two libraries makes it possible to persist the app&#39;s state, even after the app has been closed or restarted.</p><p>We declare a custom type, AppPersistStore, which contains information about the app&#39;s theme preference and a method for changing that preference.</p><p>Next, we create an instance of the MMKV instance, which will be used to persist the state of our app. The instance is stored in a constant called appPersistStorage.</p><p>We then create an object, zustandMMKVStorage, that implements the StateStorage interface. This object is responsible for providing a set of methods that allow us to interact with the appPersistStorage instance, such as setting and retrieving values.</p><p>Finally, we use the create function from the zustand library to create a hook called useAppPersistStore, which returns the current state of the app&#39;s theme preference, as well as a method for changing that preference. We use the persist middleware to ensure that the state of our app is automatically saved to the appPersistStorage instance whenever the state changes.</p><p>Whenever we call any action from this store, it will be persisted, which means that even if the app is closed or restarted, the state of the app will remain the same as it was when the app was last used. This helps to provide a consistent experience for the user, regardless of when or how the app is used.</p><p>Below is how we would end up using this hook:</p><pre>import * as React from &quot;react&quot;;<br>import { Button } from &quot;react-native&quot;;<br>import { useAppPersistStore } from &quot;./app-persist&quot;;<br><br>const Home: React.FC = () =&gt; {<br>// here we have our mmkv and zustand persist-middleware hook that we have initialized previously<br>  const { isDarkTheme, setIsDarkTheme } = useAppPersistStore();<br>  <br>  return (<br>    &lt;Button<br>      onPress={() =&gt; setIsDarkTheme(!isDarkTheme)}<br>      title={isDarkTheme ? &quot;Dark Theme&quot; : &quot;Light theme&quot;}<br>    /&gt;<br>  );<br>};<br><br>export default Home;</pre><h4>Listeners with react-native-mmkv</h4><p>We can use React Native MMKV’s listener feature to track changes in the storage. This is useful to perform certain actions whenever a particular value in the storage changes.</p><p>Here is an example of how we can use the listener in a React Native application:</p><pre>import * as React from &quot;react&quot;;<br>import { Button } from &quot;react-native&quot;;<br>import { MMKV } from &quot;react-native-mmkv&quot;;<br><br>const storage = new MMKV({ id: &quot;theme-preference&quot; });<br><br>const Home: React.FC = () =&gt; {<br>  const [isDarkTheme, setIsDarkTheme] = React.useState(false);<br><br>  React.useEffect(() =&gt; {<br>    const listener = storage.addOnValueChangedListener((changedKey) =&gt; {<br>      const newValue = storage.getString(changedKey);<br><br>      if (changedKey === &quot;isDarkTheme&quot;) {<br>        // update the theme in the app based on the updated value in the storage<br>        console.log(`New theme preference: ${newValue}`);<br>      }<br>    });<br><br>    return () =&gt; {<br>      listener.remove();<br>    };<br>  }, []);<br><br>  const toggleTheme = () =&gt; {<br>    const newPreference = !isDarkTheme;<br>    setIsDarkTheme(newPreference);<br>    storage.set(&quot;isDarkTheme&quot;, JSON.stringify(newPreference));<br>  };<br><br>  return (<br>    &lt;Button<br>      onPress={toggleTheme}<br>      title={isDarkTheme ? &quot;Dark Theme&quot; : &quot;Light Theme&quot;}<br>    /&gt;<br>  );<br>};<br><br>export default Home;</pre><p>In this example, we have created a MMKV storage with the ID theme-preference and added a listener to it using the addOnValueChangedListener method. The listener listens for changes in the storage and updates the theme in the app accordingly.</p><blockquote>The example above was intended to provide an illustration of the usage of the listener feature in React Native MMKV with a minimal amount of code, rather than being a meaningful example. In the code snippet, the listener is used to listen for changes in the storage and log the new values of the changed key.</blockquote><h4>Using with Expo</h4><p><a href="https://github.com/mrousavy/react-native-mmkv#expo">React native mmkv is indeed compatible with expo</a>, however since it is built on top of native modules, it will not work in a typical expo app (which has no native code generated) out of the box. We need to generate native code, or in other words, we need to leverage <a href="https://docs.expo.dev/workflow/prebuild/"><strong><em>prebuild</em></strong></a> feature of expo.</p><h4>Limitations</h4><p><a href="https://github.com/mrousavy/react-native-mmkv#limitations">As the library uses JSI for synchronous native methods access, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use Flipper.</a></p><h4>Conclusion</h4><p>As a react native developer, I highly recommend React Native MMKV as a storage solution for React Native applications. The library offers documentation on how to integrate it with other popular state management libraries such as jotai, redux-persist, mobx-persist, and zustand-persist-middleware, making it easy to incorporate into any project.</p><p>In comparison to React Native Async Storage, React Native MMKV offers several advantages but crucial advantages, including high performance, encryption support, and a user-friendly API. Its fully synchronous calls, with no need for async/await or Promises, make it a faster and more efficient choice.</p><p>Therefore, if you’re seeking a reliable and secure storage solution for your React Native app, I encourage you to consider using React Native MMKV.</p><h4>Resources</h4><ul><li><a href="https://github.com/mrousavy/react-native-mmkv">https://github.com/mrousavy/react-native-mmkv</a></li><li><a href="https://react-native-async-storage.github.io/async-storage/">https://react-native-async-storage.github.io/async-storage/</a></li></ul><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdbcc05a6de3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/stop-using-react-native-async-storage-fdbcc05a6de3">Stop Using React Native Async Storage</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Organizing Your React Native Codebase]]></title>
            <link>https://levelup.gitconnected.com/how-to-structure-react-native-application-679e36c63efd?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/679e36c63efd</guid>
            <category><![CDATA[mobile-application]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 18:59:03 GMT</pubDate>
            <atom:updated>2023-02-10T15:58:21.884Z</atom:updated>
            <content:encoded><![CDATA[<p>A Guide to Creating a Scalable and Maintainable Codebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lwBsDutRLClrKIQ1" /><figcaption>Photo by <a href="https://unsplash.com/@garmin2001?utm_source=medium&amp;utm_medium=referral">Garmin B</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a React Native application, organizing the codebase is crucial for maintainability and scalability. The way you structure your files and folders can greatly impact the ease with which you can work with the codebase in the future.</p><p>This article will explore the <em>feature-based</em> folder structure for a React Native application and the purpose of each folder.</p><h4>The src Folder</h4><p>The src folder is the root directory for all of your application&#39;s source code. Within this folder, you will find several other subfolders that each serve a specific purpose.</p><h4>Types</h4><p>The types folder is where you will define global types for your application. This includes module types, interface definitions, and any other custom types you need to use throughout the application.</p><p>Having a central location for all of your types makes it easier to manage and maintain them as your application grows. Additionally, it ensures that your types are consistently used across all features, reducing the risk of type-related bugs and making it easier to catch them when they do occur.</p><h4>Lib</h4><p>The lib folder is where you can keep any application-specific files that are used globally throughout the app. This can include the axios instance for making API calls, error handling services, constants, setting up query client in react-query etc.</p><p>Having these files in a centralized location makes it easier to maintain them and ensures that they are consistent across the entire application.</p><h4>Components</h4><p>The components folder is where you will keep all of your reusable components. These components should be isolated and not specific to any particular feature or domain. Examples of these types of components include headers, buttons, and list items.</p><p>Keeping these components separate from your feature-specific components makes it easier to manage and reuse them throughout your application and reduces the amount of duplication in your code.</p><h4>Hooks</h4><p>The hooks folder is where you will keep any custom hooks that are used throughout your application. A hook is a special type of function in React that allows you to reuse stateful logic across your components.</p><p>Having all of your <strong>reusable/used in multiple places </strong>custom hooks in a centralized location makes it easier to manage and maintain them, as well as reducing the risk of code duplication and making it easier to share hooks across different parts of your application.</p><h4>Localization</h4><p>The localization folder is where you will keep all of the files related to internationalization in your application. This includes language files, string constants, and any other resources needed to support multiple languages in your application.</p><p>Having these files in a centralized location, it makes it easier to manage and maintain them, as well as reducing the risk of code duplication and making it easier to support multiple languages in your application.</p><h4>Navigation</h4><p>The navigation folder is where you will keep all of the code related to navigation in your application. This includes the stacks, types, routes, and any other components or functions needed to support navigation.</p><p>By having all of your navigation code in a centralized location, it makes it easier to manage and maintain it, as well as reducing the risk of code duplication and making it easier to share navigation functionality across different parts of your application.</p><h4>Services</h4><p>The services folder is where you will keep all of the code related to the underlying infrastructure of your application. This includes code for working with push notifications, error monitoring, and any other services that are used to provide the underlying functionality of your application.</p><h4>Theme</h4><p>The theme folder is where you should store your app&#39;s styling, for example dark/light theme. Keeping your styling and theme files in one place makes it easier to manage and update your app&#39;s look and feel as needed.</p><h4>Utils</h4><p>Utility functions can be an important part of your React Native application, as they provide a way to reuse code that can be used in multiple parts of your application. The utils folder in your application is a great place to store utility functions that are used throughout your application. By centralizing these functions in one location, you can ensure that they are easy to find and use in other parts of your code. For example: react-native layout related utility functions.</p><h4>Features</h4><p>When it comes to building complex applications, it’s essential to have a clear and concise folder structure that encapsulates all of the code in one place. Having a features folder helps to achieve this as it separates all the different features of the application into distinct categories. This allows developers to quickly find and make changes to a specific feature without affecting other parts of the application.</p><p>Moreover, as the application grows and more features are added, the folder structure remains organized, making it easier for new developers to jump in and understand how the application works. The clear separation of concerns also helps to reduce the risk of bugs and improves the overall performance of the application.</p><p>Here’s what an auth folder could look like:</p><pre>src/<br>├── ...<br>└── features/<br>    ├── auth/<br>    |   ├── api/<br>    |   ├── helpers/<br>    |   ├── hooks/<br>    |   ├── screens/<br>    |   ├── services/<br>    |   └── store/<br>    └── ... (other features)</pre><p>The importance of the features folder lies in its ability to help divide the codebase into smaller, more manageable parts. Each feature has its own subfolders, such as api, helpers(or utils), hooks, screens, services, and store, that are specific to that feature. This makes it easier to understand how each feature works, as well as how they interact with one another.</p><p>The api folder contains all the API-related code specific to authentication. This makes it easier to manage the API calls and keep them organized.</p><p>The helpers folder contains helper methods or utility functions that are specific to the authentication feature. They can be used exclusively within the authentication feature and do not need to be shared with other parts of the application.</p><p>The hooks folder contains hooks that are related specifically to authentication. Since React is heavily dependent on hooks, this makes it easier to manage the hooks and keep them organized.</p><p>The screens folder contains all the screens for the authentication feature. This includes the login screen, sign-up screen, and forgotten password screen, among others.</p><p>The services folder contains services that are specific to the authentication feature. For example, you might have an authentication service that is responsible for handling user logins and sign-ups.</p><p>Finally, the store folder contains the state management code specific to the authentication feature. This can be a Redux store, a Zustand store, or any other state management library you prefer.</p><p>By breaking down the application into smaller, organized parts, it becomes much easier to manage the code and make changes to it as needed. It also helps keep the code clean and readable, making it easier for other developers to understand and work with the code.</p><h4>Sample structure of auth feature folder</h4><pre>src/<br>└── features/<br>    └── auth/<br>        ├── api/<br>        |   ├── login.ts<br>        |   ├── signup.ts<br>        |   └── refresh-token.ts<br>        ├── helpers/<br>        |   ├── validateToken.ts<br>        |   └── dataTransformer.ts<br>        ├── screens/<br>        |   ├── Login.tsx<br>        |   └── Signup.tsx<br>        ├── services/<br>        |   └── validation.ts<br>        └── store/<br>            └── auth.ts</pre><p>The auth folder is the subfolder dedicated to the authentication feature of your application. The files in this folder handle everything related to authentication and authorization, from the APIs for login and signup to the UI screens for the user to interact with.</p><p>The api folder holds the APIs for the authentication feature, such as the login.ts and signup.ts files, which handle the requests and responses for the user&#39;s login and signup requests. The refresh-token.ts file handles the refresh of the token.</p><p>The helpers folder holds helper functions that utilize in the authentication process. For example, the validateToken.ts file is used to validate the token, and the dataTransformer.ts file transforms data to and from the authentication APIs.</p><p>The screens folder holds the UI components that the user interacts with. For example, the Login.tsx and Signup.tsx files contain the UI components for the user to log in and sign up, respectively.</p><p>The hooks folder holds custom hooks related to authentication. For example, the useLoginAction.ts and useSignupForm.ts files contain hooks that help manage the state and actions related to the login and signup forms, respectively.</p><p>The services folder holds services related to authentication, such as the validation.ts file, which holds functions to validate the user&#39;s input.</p><p>The store folder holds the state management related to authentication. The auth.ts file holds the state and actions related to authentication, using a state management library like Zustand, Redux, or another one.</p><h4>CAVEAT</h4><blockquote>It is important to note that the naming conventions of the folders and files can vary from project to project and from developer to developer. The structure and organization of the folders are what’s important, rather than the exact names used for each folder. For example, the utils folder in the root of the app could also be named helpers, utilities, or instead of <em>screens</em> it could also named as <em>pages</em> or something else that makes sense for the specific project. The goal is to have a clear and consistent structure that helps developers understand the organization of the code and makes it easier to maintain and scale the application.</blockquote><h4>Type-based folder structure vs Feature-based folder structure</h4><p>Another widely adopted method for organizing a project’s codebase is the type-based folder structure, which has its own set of pros and cons. In the following section, we will compare and contrast these two folder structures visually.</p><h4><em>Comparison</em></h4><pre><strong>Feature-based folder structure:</strong><br><br>src/<br>└── features/<br>    ├── auth/<br>    |   ├── api/<br>    |   │     ├── register.tsx<br>    |   │     ├── login.tsx<br>    |   │     ├── types.tsx<br>    |   │     └── helpers.tsx<br>    |   ├── helpers/<br>    |   ├── hooks/<br>    |   └── screens/<br>    |   │     ├── LoginScreen.tsx<br>    |   │     ├── SignupScreen.tsx<br>    |   │     ├── WelcomeScreen.tsx<br>    |   │     └── HomeScreen.tsx<br>    |   ├── services/<br>    |   └── store/<br>    ├── todo/<br>    |   └── screens/<br>    |   │    └── TodoListScreen.tsx<br>    |   ├── services/<br>    |   └── store/<br>    └── ... (other features)<br><br><strong>Type-based folder structure:</strong><br><br>src/<br>├── screens/<br>|   ├── LoginScreen.tsx<br>|   ├── SignupScreen.tsx<br>|   ├── TodoListScreen.tsx<br>|   ├── WelcomeScreen.tsx<br>|   └── HomeScreen.tsx<br>├── api/<br>|   └── auth/<br>|       ├── register.ts<br>|       ├── login.ts<br>|       ├── types.ts<br>|       └── helpers.ts<br></pre><p>As can be seen above, in the type-based folder structure, the screens are separated from the API calls and helpers, which can make it harder to understand the codebase. Notice how we might end up placing unrelated screens such as LoginScreen.tsx and TodoListScreen.tsx under the same folder in the type-based folder structure. Additionally, <strong><em>it can also make it harder to maintain the code as the related code is not grouped together in one place.</em></strong> While in the feature-based folder structure, all of the code related to authentication, including the screens, API calls, helpers, and services, are grouped together in one auth folder. This makes it easier to understand the codebase, as all of the related code is located in one place. This approach allows for better encapsulation of code and makes the project scalable and flexible for future changes.</p><h4>The latest picture with a feature-based folder structure</h4><p>Below is how it would look in the end with the feature-based folder structure with dummy files:</p><pre><strong>Feature-based folder structure:</strong><br><br>src/<br>├── components/<br>│   ├── Button.tsx<br>│   └── Header.tsx<br>├── hooks/<br>│   └── useHeader.ts<br>├── localization/<br>│   ├── languages.ts<br>│   └── locales.ts<br>├── lib/<br>│   ├── axios-instance.ts<br>│   └── constants.ts<br>├── navigation/<br>│   ├── root-navigator.tsx<br>│   └── auth-stack.tsx<br>├── services/<br>│   ├── notification.ts<br>│   └── logging.ts<br>├── theme/<br>│   └── index.ts<br>├── types/<br>│   ├── env.d.ts<br>│   └── react-augment.d.ts<br>├── utils/<br>│   └── layout.ts<br>└── features/<br>    ├── auth/<br>    │   ├── api/<br>    │   │   ├── login.ts<br>    │   │   ├── signup.ts<br>    │   │   └── refresh-token.ts<br>    │   ├── helpers/<br>    │   │   ├── validateToken.ts<br>    │   │   └── dataTransformer.ts<br>    │   ├── hooks/<br>    │   │   ├── useLoginAction.ts<br>    │   │   └── useSignupForm.ts<br>    │   ├── screens/<br>    │   │   ├── Login.tsx<br>    │   │   └── Signup.tsx<br>    │   ├── services/<br>    │   │   └── validation.ts<br>    │   └── store/<br>    │       └── auth.ts (zustand, redux, jotai etc.)<br>    └── ... (other features)</pre><blockquote>The files that were added to the various folders above (e.g. button.tsx, header.tsx in the components folder, useHeader.ts in the hooks folder, etc.) are meant to serve as examples and should not be taken as 100% accurate. The purpose of including these files is to provide a visual representation of the folder structure and help to better understand the organization of the codebase. The actual implementation may vary based on the specific requirements of the project. The focus of this article is on the feature-based folder structure and how it can help to build a scalable and organized codebase, rather than on the specific details of individual files.</blockquote><h4>Conclusion</h4><p>In my opinion, the feature-based folder structure is a useful approach for organizing React/React Native projects. By breaking down the code into separate features, I find it easier to maintain, understand, and develop the application. This structure allows for better encapsulation of code, making the project scalable and flexible for future changes. Of course, this is not a one-size-fits-all solution, and the exact structure may vary depending on the size and complexity of the project. However, the key idea is to keep a clear separation between different features and their respective components, services, and data. In my experience, this structure has helped me build and maintain well-organized projects that are capable of handling growth and change over time. I wanted to share this approach with others who may find it useful as well.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679e36c63efd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-structure-react-native-application-679e36c63efd">Organizing Your React Native Codebase</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-end testing in React Native]]></title>
            <link>https://levelup.gitconnected.com/end-to-end-testing-in-react-native-79d23dbf0168?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d23dbf0168</guid>
            <category><![CDATA[end-to-end-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 12:01:21 GMT</pubDate>
            <atom:updated>2023-07-03T15:56:25.853Z</atom:updated>
            <content:encoded><![CDATA[<p>Write cross-platform end-to-end tests in Javascript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YDzi2yL6gRf0eBfx" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing tests for the code has been an essential part of programming nowadays. There are different types of software testing methodologies, such as <em>unit tests, integration tests, </em>and<em> end-to-end tests. T</em>his article will cover how we can apply <strong><em>end-to-end</em></strong> testing on a simple react-native app.</p><p>We will be using <a href="https://github.com/wix/Detox"><strong>Detox</strong></a> library which is developed and maintained by the <a href="https://github.com/wix"><strong>Wix</strong></a> team.</p><p>The app is pretty straightforward! It allows users to <em>like</em> their favorite Nintendo 64 app. That said, there is actually one certain behavior to test in the app. <em>Like</em> functionality!</p><h4>User Story</h4><p>Let’s list all of what can be the user actions for this functionality:</p><ol><li>User opens the app.</li><li>User sees the game card, and the game card has a <em>like</em> button and a <em>total</em> <em>number of likes text </em>available on it. (To compare the text after the user action)</li><li>User presses on the <em>like</em> button.</li><li>User notices that <em>like</em> text changed. In this case, the number of likes is increased by one.</li></ol><pre><strong><em>CAVEAT: </em></strong><em>This user story can be considered an integration test in theory. Yet since the app itself is only responsible for allowing users to like their game, it is treated as end-to-end testing.</em></pre><h4><strong>Code</strong></h4><p>We will be generating our code whilst we walk through the user stories in order. Each code block will eventually correspond to a specific user story.</p><ol><li><strong>User opens the app.</strong></li></ol><pre>const detox = require(&quot;detox&quot;);<br>const config = require(&quot;../package.json&quot;).detox;<br><br>// before doing any test, ensure the app is launched by the device.<br>beforeAll(async () =&gt; {<br>  await detox.init(config);<br>  await device.launchApp();<br>});</pre><p>2. <strong>User sees the game card, and the game card has a <em>like</em> button and a <em>total</em> <em>number of likes text </em>available on it. (To compare the text after the user action)</strong></p><pre>  it(&quot;Game card has the like text and button are available on the screen&quot;, async () =&gt; {<br>    // test if the elements are on the screen<br>    await expect(element(by.id(&quot;game-card-like-text-1&quot;))).toExist();<br>    await expect(element(by.id(&quot;game-card-like-button-1&quot;))).toExist();<br><br>    // test game card has the like text available on the screen<br>    const likeTextAttrs = await element(<br>      by.id(&quot;game-card-like-text-1&quot;),<br>    ).getAttributes();<br><br>    await expect(element(by.text(likeTextAttrs.text))).toExist();<br>  });</pre><p>3.<strong> User presses on the <em>like</em> button.</strong></p><pre>it(&quot;pressing the like button&quot;, async () =&gt; {<br>  // Tap to the like button to increase like count<br>  await element(by.id(&quot;game-card-like-button-1&quot;)).tap();<br>});</pre><p>4. <strong>User notices that <em>like</em> text changed. In this case, the number of likes is increased by one.</strong></p><pre>it(&quot;pressing the like button of the first game card should increase the like count by one&quot;, async () =&gt; {<br>    // get like text(like count) before the like button is &quot;tapped&quot;<br>    const beforeLikeTextAttrs = await element(<br>      by.id(&quot;game-card-like-text-1&quot;),<br>    ).getAttributes();<br><br>    // Tap to the like button to increase like count<br>    await element(by.id(&quot;game-card-like-button-1&quot;)).tap();<br><br>    // calculate final like text(count)<br>    const increasedLike = Number(beforeLikeTextAttrs.text) + 1;<br><br>    // get updated like text<br>    const afterLikeText = await element(<br>      by.id(&quot;game-card-like-text-1&quot;),<br>    ).getAttributes();<br><br>    // test whether the like text(count) has been increased<br>    await expect(element(by.text(afterLikeText.text.toString()))).toHaveText(<br>      increasedLike.toString(),<br>    );<br>  });<br>});</pre><h4><strong>Full code</strong></h4><pre>// For more info on how to write Detox tests, see the official docs:<br>// https://github.com/wix/Detox/blob/master/docs/README.md<br><br>const { reloadApp } = require(&quot;./reload&quot;);<br><br>describe(&quot;Example&quot;, () =&gt; {<br>  beforeEach(async () =&gt; {<br>    await reloadApp();<br>  });<br><br>  it(&quot;First game card has the like text and button are available on the screen&quot;, async () =&gt; {<br>    // tests if the elements are on the screen<br>    await expect(element(by.id(&quot;game-card-like-text-1&quot;))).toExist();<br>    await expect(element(by.id(&quot;game-card-like-button-1&quot;))).toExist();<br><br>    // test game card has the like text available on the screen<br>    const likeTextAttrs = await element(<br>      by.id(&quot;game-card-like-text-1&quot;),<br>    ).getAttributes();<br><br>    await expect(element(by.text(likeTextAttrs.text))).toExist();<br>  });<br><br>  it(&quot;pressing the like button of the first game card should increase the like count by one&quot;, async () =&gt; {<br>    // get like text(like count) before the like button is &quot;tapped&quot;<br>    const beforeLikeTextAttrs = await element(<br>      by.id(&quot;game-card-like-text-1&quot;),<br>    ).getAttributes();<br><br>    // Tap to the like button to increase like count<br>    await element(by.id(&quot;game-card-like-button-1&quot;)).tap();<br><br>    // calculate final like text(count)<br>    const increasedLike = Number(beforeLikeTextAttrs.text) + 1;<br><br>    // get updated like text<br>    const afterLikeText = await element(<br>      by.id(&quot;game-card-like-text-1&quot;),<br>    ).getAttributes();<br><br>    // test whether the like text(count) has been increased<br>    await expect(element(by.text(afterLikeText.text.toString()))).toHaveText(<br>      increasedLike.toString(),<br>    );<br>  });<br>});</pre><h4><strong>Demo</strong></h4><p>Let’s see everything in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*p9YIVHUK5tLqVmMVPI67Tg.gif" /></figure><p>This article has covered the preliminaries of end-to-end testing in react-native apps. For the sake of simplicity, the app itself is basic enough to demonstrate fundamental aspects of end-to-end testing. Indeed, it can be more convoluted than this one in real-life/production applications.</p><p>You can take a look at the final source code of this app using the link below.</p><p>Have a bug-free day everyone!</p><p><a href="https://github.com/tarikpnr/react-native-n64-voter-app">Github source code</a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d23dbf0168" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/end-to-end-testing-in-react-native-79d23dbf0168">End-to-end testing in React Native</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Structure Navigation in React Native With Typescript]]></title>
            <link>https://medium.com/better-programming/react-navigation-with-typescript-fa7805f52ab0?source=rss-9c9b54aeb0a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7805f52ab0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tarik]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 12:02:08 GMT</pubDate>
            <atom:updated>2023-07-03T15:54:12.909Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leverage the typings — React Navigation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iMhaqe1HBwocGhBK" /><figcaption>Photo by <a href="https://unsplash.com/@hendrikmorkel?utm_source=medium&amp;utm_medium=referral">Hendrik Morkel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Building navigation has been the fundamental feature of any mobile application these days. When it comes to React Native world, we have <a href="https://reactnavigation.org/">React Navigation</a> in our pocket.</p><p>This article will go through how a typical React Navigation can be implemented using TypeScript meanwhile comparing different strategies of TypeScript usage.</p><p>And more importantly, it will also cover how we can make the most out of TypeScript features to be able to build a more scalable architecture on navigation.</p><p><em>Caveat: The examples in this article have been derived using @react-navigation@6.x version.</em></p><p><em>Caveat: The methods/strategies that will be covered in this article are not indispensable ones that you must strictly follow but they are just my predilections and found them useful to share with the readers of this article. </em><a href="https://reactnavigation.org/docs/typescript"><em>React Navigation has already an amazing well-documented section regarding typescript usage.</em></a><em> That being said, you can already build an awesome react-navigation typescript structure by just following the </em><a href="https://reactnavigation.org/docs/typescript/"><em>this documentation</em></a><em>.</em></p><h4>Creating Stack Navigator</h4><p>Let‘s take a look at how to create a <a href="https://reactnavigation.org/docs/stack-navigator/">stack navigator</a> using the <a href="https://reactnavigation.org/">React Navigation </a>package.</p><p>See the example below taken from <a href="https://reactnavigation.org/docs/stack-navigator/#api-definition">React Navigation</a>;</p><pre>import { createStackNavigator } from &#39;@react-navigation/stack&#39;;<br><br>const Stack = createStackNavigator();<br><br>function MyStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      &lt;Stack.Screen name=&quot;Home&quot; component={Home} /&gt;<br>      &lt;Stack.Screen name=&quot;Notifications&quot; component={Notifications} /&gt;<br>      &lt;Stack.Screen name=&quot;Profile&quot; component={Profile} /&gt;<br>      &lt;Stack.Screen name=&quot;Settings&quot; component={Settings} /&gt;<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p>As can be seen that there is nothing specific about TypeScript here, let’s add a bit of TypeScript to this code snippet.</p><pre>import { createStackNavigator } from &#39;@react-navigation/stack&#39;;<br>import * as React from &#39;react&#39;;<br>import { View } from &#39;react-native&#39;;<br><br>type AppStackParamList = {<br>  Home: undefined;<br>  Notifications: undefined;<br>  Profile: undefined;<br>  Settings: undefined;<br>};<br><br>const Home = () =&gt; &lt;View /&gt;;<br>const Notifications = () =&gt; &lt;View /&gt;;<br>const Profile = () =&gt; &lt;View /&gt;;<br>const Settings = () =&gt; &lt;View /&gt;;<br><br>const Stack = createStackNavigator&lt;AppStackParamList&gt;();<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      &lt;Stack.Screen name=&quot;Home&quot; component={Home} /&gt;<br>      &lt;Stack.Screen name=&quot;Notifications&quot; component={Notifications} /&gt;<br>      &lt;Stack.Screen name=&quot;Profile&quot; component={Profile} /&gt;<br>      &lt;Stack.Screen name=&quot;Settings&quot; component={Settings} /&gt;<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}<br>@tarikfp</pre><p>In the above, we have added the ParamList type for createStackNavigator. But hey, how do we know that createStackNavigator takes the generic type? There are a couple of ways to figure it out. It has always been good practice to review the <a href="https://reactnavigation.org/docs/typescript/#type-checking-the-navigator">documentation</a> first. In this given example, you will already notice that there is already a section for it in the docs.</p><p>On the other hand, assuming that this specific typing of createStackNavigator is not documented on the website, then a possible way of determining whether the function has the typing would be just jumping to the type definition of the function. It can be intimidating at first since there will be lots of types, interfaces, generics flying around but the more you get into the habit of jumping to the type definition, it will be much less overwhelming.</p><h4><strong>Update!</strong></h4><p>If you wanna deal with extra complexity with typescript and also want to ignore brilliant TS utility from React team (React.ComponentProps), you can continue to read to the end of this article.</p><p>But I am afraid, this section might be the end!</p><p>We will be able to retrieve the typings for each stack screen and their configuration with React.ComponentProps&lt;typeof YourStack.Screen&gt; And the result will be simply amazing.</p><p>See below for complete example:</p><pre>import { createStackNavigator } from &quot;@react-navigation/stack&quot;;<br>import * as React from &quot;react&quot;;<br>import { View } from &quot;react-native&quot;;<br><br>type AppStackParamList = {<br>  Home: undefined;<br>  Notifications: undefined;<br>  Profile: undefined;<br>  Settings: undefined;<br>};<br><br>const Home = () =&gt; &lt;View /&gt;;<br>const Notifications = () =&gt; &lt;View /&gt;;<br>const Profile = () =&gt; &lt;View /&gt;;<br>const Settings = () =&gt; &lt;View /&gt;;<br><br>const Stack = createStackNavigator&lt;AppStackParamList&gt;();<br><br>const routes: Array&lt;React.ComponentProps&lt;typeof Stack.Screen&gt;&gt; = [<br>  {<br>    name: &quot;Home&quot;,<br>    component: Home,<br>  },<br>  {<br>    name: &quot;Notifications&quot;,<br>    component: Notifications,<br>  },<br>  {<br>    name: &quot;Profile&quot;,<br>    component: Profile,<br>  },<br>  {<br>    name: &quot;Settings&quot;,<br>    component: Settings,<br>  },<br>];<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      {routes.map((routeConfig) =&gt; (<br>        &lt;Stack.Screen key={routeConfig.name} {...routeConfig} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p>And yes, it will still have the intellisense, it will still warn you if you put a non-related<em> (or i.e: a screen that is not in your stack type declaration)</em> screen to your stack, such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkS3Ay_QPrWIDMZZCsOpZQ.png" /><figcaption>Invalid screen</figcaption></figure><p>Intellisense will be there as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWJw4fN3Fs0IpOd-rSAIQA.png" /></figure><p>It is also more clean, configurable, and dynamic:</p><pre>  const getAuthStackRoutes = (<br>    // other parameters...<br>    theme: ThemeType<br>  ): Array&lt;React.ComponentProps&lt;typeof Stack.Screen&gt;&gt; =&gt; {<br>    // more business logic...<br><br>    return [<br>      {<br>        name: &quot;Home&quot;,<br>        component: Home,<br>        options: {<br>          headerStyle: {<br>            backgroundColor: theme.colors.primary,<br>            // other theme stylings...<br>          },<br>        },<br>      },<br>    ];<br>  };</pre><p>In conclusion, this approach allows us to manage complex navigation structures easily<em>(at least when we compare this specific approach with other approaches in this article)</em>. It is because while you will have cleaner JSX, you will be also able to configure your routesin a more dynamic, modular way.</p><h4>Taking usage of TypeScript one step ahead</h4><p>It is indeed not limited to declaring only generic type of createStackNavigator. How about the type of children elements that Stack.Navigator will have? Although t<a href="https://reactnavigation.org/docs/typescript/#type-checking-screens">his concept is already pretty well defined in the official documentation</a>, let’s see below how we can play around with it to have a more decoupled way of creating the structure.</p><pre>import type {<br>  RouteConfig,<br>  StackNavigationState,<br>} from &#39;@react-navigation/core&#39;;<br>import {<br>  createStackNavigator,<br>  StackNavigationEventMap,<br>  StackNavigationOptions,<br>} from &#39;@react-navigation/stack&#39;;<br>import * as React from &#39;react&#39;;<br>import { View } from &#39;react-native&#39;;<br><br>// stack param list type<br>type AppStackParamList = {<br>  Home: undefined;<br>  Notifications: undefined;<br>  Profile: undefined;<br>  Settings: undefined;<br>};<br><br>// type of the single route in app stack<br>type AppStackRoutesType = RouteConfig&lt;<br>  AppStackParamList,<br>  keyof AppStackParamList,<br>  StackNavigationState&lt;AppStackParamList&gt;,<br>  StackNavigationOptions,<br>  StackNavigationEventMap<br>&gt;;<br><br>// mocking the screen components for the sake of example<br>const Home = () =&gt; &lt;View /&gt;;<br>const Notifications = () =&gt; &lt;View /&gt;;<br>const Profile = () =&gt; &lt;View /&gt;;<br>const Settings = () =&gt; &lt;View /&gt;;<br><br>// strictly typed array of app stack routes<br>const appStackRoutes: Array&lt;AppStackRoutesType&gt; = [<br>  {<br>    name: &#39;Home&#39;,<br>    component: Home,<br>  },<br>  {<br>    name: &#39;Notifications&#39;,<br>    component: Notifications,<br>  },<br>  {<br>    name: &#39;Profile&#39;,<br>    component: Profile,<br>  },<br>  {<br>    name: &#39;Settings&#39;,<br>    component: Settings,<br>  },<br>];<br><br>const Stack = createStackNavigator&lt;AppStackParamList&gt;();<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      {/** mapping the app stack routes */}<br>      {appStackRoutes.map((stackRoute) =&gt; (<br>        &lt;Stack.Screen key={stackRoute.name} {...stackRoute} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p>Oops, there is so much going on here… Let’s divide each code block to separate parts.</p><pre><br>import type {<br>  RouteConfig,<br>  StackNavigationState,<br>} from &#39;@react-navigation/core&#39;;<br>import {<br>  createStackNavigator,<br>  StackNavigationEventMap,<br>  StackNavigationOptions,<br>} from &#39;@react-navigation/stack&#39;;<br>import * as React from &#39;react&#39;;<br>import { View } from &#39;react-native&#39;;</pre><p>At the top of the code snippet, we are importing the necessary modules. These imports include types, functions, and other necessary stuff. They are not interesting but necessary :)</p><pre>// mocking the screen components for the sake of example<br>const Home = () =&gt; &lt;View /&gt;;<br>const Notifications = () =&gt; &lt;View /&gt;;<br>const Profile = () =&gt; &lt;View /&gt;;<br>const Settings = () =&gt; &lt;View /&gt;;</pre><p>Above, we are importing <a href="https://reactnative.dev/docs/view">View</a> component from react-native so that the example is demonstrable in a more simple way.</p><pre>// type of the single route in app stack<br>type AppStackRoutesType = RouteConfig&lt;<br>  AppStackParamList,<br>  keyof AppStackParamList,<br>  StackNavigationState&lt;AppStackParamList&gt;,<br>  StackNavigationOptions,<br>  StackNavigationEventMap<br>&gt;;</pre><p>Now, here comes the interesting part. The RouteConfig which is imported from @react-navigation/core takes exactly five types as a <a href="https://www.typescriptlang.org/docs/handbook/2/generics.html">generic type</a>. And this particular type definition is not documented on the official react-navigation website, nonetheless, you can already figure this type definition out by just using the method of jumping to the type definition as we mentioned above.</p><p>Even though it might seem redundant/not necessary to have it on a typical react-native typescript project, it comes with several benefits which will be covered below section.</p><h4><a href="https://code.visualstudio.com/docs/editor/intellisense">IntelliSense</a></h4><p>Since we have a strictly typed stack routes(aka app routes) array, every element of the array is now obliged to stick with the type definition of the array. This means IntelliSense will work out of the box when adding a new element to the array.</p><p>Moreover, applying this type enforces us to update AppStackRoutesType<em> </em>whenever there will be a new element to be added to the app routes. Otherwise, we would not be able to add a new element that does not exist in the AppStackRoutesType(AppStackParamList)<em>.</em></p><h4>Mapping the routes</h4><p>Here comes the last part, we are creating the stack navigator using createStackNavigator. Then simply it is just a matter of mapping the array we created above along with the strict type of it.</p><p>We can eventually trust every element of our array, it will have correctly typed elements, thus it is safe to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread syntax</a>.</p><pre>const Stack = createStackNavigator&lt;AppStackParamList&gt;();<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      {/** mapping the app stack routes */}<br>      {appStackRoutes.map((stackRoute) =&gt; (<br>        &lt;Stack.Screen key={stackRoute.name} {...stackRoute} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><h4>Was it really the last part?</h4><p>Well… No!</p><p>We can still improve our typings on the example we’ve covered.</p><pre>// generic stack routes type<br>export type StackRoutesType&lt;ParamList extends ParamListBase&gt; = Array&lt;<br>  RouteConfig&lt;<br>    ParamList,<br>    keyof ParamList,<br>    StackNavigationState&lt;ParamList&gt;,<br>    StackNavigationOptions,<br>    StackNavigationEventMap<br>  &gt;<br>&gt;;<br><br>type AppStackRoutesType = StackRoutesType&lt;AppStackParamList&gt;;<br><br>// mocking the screen components for the sake of example<br>const Home = () =&gt; &lt;View /&gt;;<br>const Notifications = () =&gt; &lt;View /&gt;;<br>const Profile = () =&gt; &lt;View /&gt;;<br>const Settings = () =&gt; &lt;View /&gt;;<br><br>// strictly typed array of app stack routes<br>const appStackRoutes: AppStackRoutesType = [<br>  {<br>    name: &#39;Home&#39;,<br>    component: Home,<br>  },<br>  {<br>    name: &#39;Notifications&#39;,<br>    component: Notifications,<br>  },<br>  {<br>    name: &#39;Profile&#39;,<br>    component: Profile,<br>  },<br>  {<br>    name: &#39;Settings&#39;,<br>    component: Settings,<br>  },<br>];</pre><p>The difference you might have noticed is that we have StackRoutesType which takes a generic type and equals the type that we have already seen before. But what is the benefit here you may ask. Better to answer this question in a visualized way.</p><pre>// too much duplicated code...<br><br>type AppStackRoutesType = RouteConfig&lt;<br>  AppStackParamList,<br>  keyof AppStackParamList,<br>  StackNavigationState&lt;AppStackParamList&gt;,<br>  StackNavigationOptions,<br>  StackNavigationEventMap<br>&gt;;<br><br>type OtherStackRoutesType = RouteConfig&lt;<br>  OtherStackParamList,<br>  keyof OtherStackParamList,<br>  StackNavigationState&lt;OtherStackParamList&gt;,<br>  StackNavigationOptions,<br>  StackNavigationEventMap<br>&gt;;<br><br>type AnotherStackRoutesType = RouteConfig&lt;<br>  AnotherStackParamList,<br>  keyof AnotherStackParamList,<br>  StackNavigationState&lt;AnotherStackParamList&gt;,<br>  StackNavigationOptions,<br>  StackNavigationEventMap<br>&gt;;</pre><p>If we were not to choose to use generic StackRoutesType<em>, </em>we would have to duplicate typings for every stack we have in the app.</p><p>Therefore, this would be a nightmare as the app gets bigger. <em>(here the notion is, number of stacks in the app and the complexity of the app are directly proportional, in fact, it is not a always 100% valid assumption, nevertheless it is suitable for this specific example)</em></p><pre>// generic stack routes type<br>export type StackRoutesType&lt;ParamList extends ParamListBase&gt; = Array&lt;<br>  RouteConfig&lt;<br>    ParamList,<br>    keyof ParamList,<br>    StackNavigationState&lt;ParamList&gt;,<br>    StackNavigationOptions,<br>    StackNavigationEventMap<br>  &gt;<br>&gt;;<br><br>// becomes one line typings for each stack<br>type AppStackRoutesType = StackRoutesType&lt;AppStackParamList&gt;;<br>type OtherStackRoutesType = StackRoutesType&lt;OtherStackParamList&gt;;<br>type AnotherStackRoutesType = StackRoutesType&lt;AnotherStackParamList&gt;;</pre><p>On the other hand, see above how it becomes simpler and clean now when using generic type.</p><h3>Latest pictures</h3><p>Let’s compare how a typical Stack function would look in two different scenarios:</p><p><em>Picture 1: Rendering whole stack screens one by one in JSX.</em></p><pre>// ...imports, components<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      &lt;Stack.Screen name=&quot;Home&quot; component={Home} /&gt;<br>      &lt;Stack.Screen name=&quot;Notifications&quot; component={Notifications} /&gt;<br>      &lt;Stack.Screen name=&quot;Profile&quot; component={Profile} /&gt;<br>      &lt;Stack.Screen name=&quot;Settings&quot; component={Settings} /&gt;<br>      {/** n more screens... */}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p><em>Picture 2: Rendering screens using the stack routes array created using the strictly typed typescript. 🎉</em></p><pre>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      {appStackRoutes.map((stackRoute) =&gt; (<br>        &lt;Stack.Screen key={stackRoute.name} {...stackRoute} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><h4>One more thing… What about Navigator props</h4><p>We might have one more thing left to consider which is props of the stack navigator. Looking at the below StackNavigator<em>, </em>there exists a chunk of configurations for a single navigator. Why not have these configurations decoupled from JSX?</p><pre>import type {<br>  DefaultNavigatorOptions,<br>  ParamListBase,<br>  StackNavigationState,<br>} from &#39;@react-navigation/core&#39;;<br>import {<br>  StackNavigationEventMap,<br>  StackNavigationOptions,<br>} from &#39;@react-navigation/stack&#39;;<br>// other necessary imports for screens...<br><br>// generic typing for stack navigator options<br>type StackNavigatorOptions&lt;ParamList extends ParamListBase&gt; =<br>  DefaultNavigatorOptions&lt;<br>    ParamList,<br>    StackNavigationState&lt;ParamList&gt;,<br>    StackNavigationOptions,<br>    StackNavigationEventMap<br>  &gt;;<br><br>// omit the children as it corresponds to stack screen<br>const appStackNavigatorProps: Omit&lt;<br>  StackNavigatorOptions&lt;AppStackParamList&gt;,<br>  &#39;children&#39;<br>&gt; = {<br>  initialRouteName: &#39;Home&#39;,<br>  screenOptions: {<br>    headerShown: false,<br>    cardOverlayEnabled: true,<br>    gestureEnabled: false,<br>    cardStyle: {<br>      backgroundColor: &#39;royalblue&#39;,<br>    },<br>    headerLeftContainerStyle: {<br>      backgroundColor: &#39;firebrick&#39;,<br>    },<br>    presentation: &#39;modal&#39;,<br>    headerTitleStyle: {<br>      fontSize: 24,<br>      color: &#39;olivedrab&#39;,<br>    },<br>  },<br>  // ...rest<br>};<br><br>// screen components and stack routes...<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator {...appStackNavigatorProps}&gt;<br>      {appStackRoutes.map((stackRoute) =&gt; (<br>        &lt;Stack.Screen key={stackRoute.name} {...stackRoute} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p>Starting from Line 13, we should be already familiar with why we use generic type. The bare difference in typing with the stack routes here might be the DefaultNavigatorOptions type, which is imported from @react-navigation/core. The name of the type itself is even self-explanatory, it is options for the navigator.</p><p>Similar to <em>RouteConfig </em>type<em> </em>we have mentioned above<em>, </em>it takes also multiple generic types. Besides this, bear in mind that we are explicitly o<a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys"><em>mitting</em></a><em> </em>the children key as we are already rendering Stack.Navigator<em> </em>children which correspond to Stack.Screen<em>.</em></p><p>On Line 22, we are creating a brand new object (or it can be a function, as long as it returns an object that satisfies the navigator options type) which will represent the options of our navigator.</p><p>As a result, on Line 50, this object can be safely used with spread syntax as long as it satisfies the given type.</p><p>Much cleaner JSX… IMO…</p><h4>Latest pictures - Navigator props</h4><p>Let’s again compare how a typical Stack function would look in two different scenarios:</p><p><em>Picture 1: Having stack navigator configurations in JSX.</em></p><pre>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator<br>      initialRouteName=&quot;Home&quot;<br>      screenOptions={{<br>        headerShown: false,<br>        cardOverlayEnabled: true,<br>        gestureEnabled: false,<br>        cardStyle: {<br>          backgroundColor: &#39;royalblue&#39;,<br>        },<br>        headerLeftContainerStyle: {<br>          backgroundColor: &#39;firebrick&#39;,<br>        },<br>        presentation: &#39;modal&#39;,<br>        headerTitleStyle: {<br>          fontSize: 24,<br>          color: &#39;olivedrab&#39;,<br>        },<br>      }}<br>      // rest...<br>    &gt;<br>      {appStackRoutes.map((stackRoute) =&gt; (<br>        &lt;Stack.Screen key={stackRoute.name} {...stackRoute} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p><em>Picture 2: Having stack navigator configurations decoupled from JSX.</em></p><pre>// ...<br><br>function AppStack() {<br>  return (<br>    &lt;Stack.Navigator {...appStackNavigatorProps}&gt;<br>      {appStackRoutes.map((stackRoute) =&gt; (<br>        &lt;Stack.Screen key={stackRoute.name} {...stackRoute} /&gt;<br>      ))}<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}</pre><p>In this article, we have covered how we can actually leverage TypeScript and achieve a cleaner way to structure our react-native navigators.</p><p>Have a bug-free day everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7805f52ab0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/react-navigation-with-typescript-fa7805f52ab0">How to Structure Navigation in React Native With Typescript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>