<?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 Hassem Mahboob on Medium]]></title>
        <description><![CDATA[Stories by Hassem Mahboob on Medium]]></description>
        <link>https://medium.com/@hassem_mahboob?source=rss-1b9ee856676e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2mmnTAzZi3Owh_1X.jpg</url>
            <title>Stories by Hassem Mahboob on Medium</title>
            <link>https://medium.com/@hassem_mahboob?source=rss-1b9ee856676e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:42:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hassem_mahboob/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[Mastering Socket Listeners in React Native and React.js]]></title>
            <link>https://medium.com/@hassem_mahboob/mastering-socket-listeners-in-react-native-and-react-js-872be6e4798c?source=rss-1b9ee856676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/872be6e4798c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <dc:creator><![CDATA[Hassem Mahboob]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 09:39:05 GMT</pubDate>
            <atom:updated>2024-09-10T09:39:05.204Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-paced world of real-time applications, socket listeners have become an essential tool for building dynamic and interactive user experiences. Whether it’s a chat app, a live notification system, or a real-time feed, socket listeners allow seamless two-way communication between the server and the client.</p><p>This blog will walk you through how to implement socket listeners in <strong>React Native</strong> and <strong>React.js</strong> from basic setup to advanced optimizations.</p><h3>What are Socket Listeners?</h3><p>Socket listeners facilitate real-time, two-way communication over <strong>WebSockets</strong> between the server and client. Unlike traditional HTTP requests, WebSockets keep the connection open, allowing the server to push updates to the client without needing constant polling.</p><h3>1. Creating a Socket Connection</h3><p>Before you can use socket listeners, you first need to establish a connection between your client (React or React Native) and the server. <strong>Socket.IO</strong> is a popular library that simplifies WebSocket connections.</p><pre>export let socket = null;<br><br>export const socketConnection = async (token) =&gt; {<br>  try {<br>    socket = io(process.env.NEXT_PUBLIC_API_SOCKET, {<br><br>      auth: {<br>        authorization: token,<br>      },<br>    });<br>  } catch (error) {<br>    console.error(&#39;Error creating socket connection:&#39;, error);<br>  }<br>};</pre><p>Replace process.env.NEXT_PUBLIC_API_SOCKET with your actual server’s URL. This simple code snippet establishes a connection with your server.</p><h4>Security Consideration: Using JWT (Optional but Recommended)</h4><p>Although not mandatory, it’s good practice to use <strong>JWT authentication</strong> for added security in socket connections. You can pass the user’s token like this:</p><h3>2. Using WebSockets Instead of Polling</h3><p>By default, Socket.IO may fall back to <strong>polling</strong>, which periodically checks for updates. For optimal real-time performance, it’s better to enforce <strong>WebSockets</strong> as the primary transport.</p><pre>export const setSocket = async (token) =&gt; {<br><br>  try {<br>    socket = io(process.env.NEXT_PUBLIC_API_SOCKET, {<br>      auth: {<br>        authorization: token,<br>      },<br>      transports: [&#39;websocket&#39;],<br>      EIO: 4,<br>      secure: true,<br>    });<br>  } catch (error) {<br>    console.error(&#39;Error creating socket connection:&#39;, error);<br>  }<br><br>};</pre><p>This configuration ensures that WebSockets are used, avoiding the overhead of polling.</p><h3>3. Connecting to Specific Listeners</h3><p>Once the socket connection is established, you can start listening for specific events sent from the server. This is done using socket.on(), where you specify the event name and a callback to handle the response.</p><pre><br>   socket.on(&#39;new_message&#39;, (message) =&gt; {<br>    console.log(&#39;New message received:&#39;, message);<br>    });</pre><p>In this example, the client listens for new_message events and logs the message content whenever it&#39;s received and you can start this listener in your useEffect or on any onPress as per your needs.</p><h3>4. Avoiding Duplicate Listeners</h3><p>To prevent the same event from being listened to multiple times, it’s essential to check if a listener is already registered before adding it again. Adding the same listener multiple times could result in duplicate event handling.</p><pre>if (!socket.hasListeners(&#39;new_message&#39;)) {<br><br>    socket.on(&#39;new_message&#39;, (message) =&gt; {<br>        console.log(&#39;New message:&#39;, message);<br>    });<br><br>}</pre><p>This ensures that the chat_message listener is only added once, preventing the application from handling the same event multiple times.</p><h3>5. Removing a Specific Listener Or All Listeners</h3><p>At times, you may want to stop listening for a particular event. This can be done using socket.off().</p><pre>socket.off(&#39;new_message&#39;);</pre><p>If you want to remove all listeners associated with a socket, use the</p><pre>socket.removeAllListeners();</pre><h3><strong>6.</strong> <strong>Closing the Socket Connection</strong></h3><p>When the socket is no longer needed (for example, when the user logs out or navigates away from the page), it’s a good practice to close the connection.</p><pre>socket.close();</pre><p>Closing the socket ensures that no resources are wasted on maintaining an unnecessary connection.</p><h3>Advanced Topics</h3><h4>Error Handling in WebSockets</h4><p>Network issues or server downtime can disrupt socket connections. You should always handle errors and reconnections to ensure a smooth user experience.</p><pre>socket.on(&#39;connect_error&#39;, (err) =&gt; {<br>    console.error(&#39;Connection Error:&#39;, err);<br>});<br><br>socket.on(&#39;disconnect&#39;, () =&gt; {<br>    console.log(&#39;Socket disconnected, reconnecting...&#39;);<br>    socket.connect();<br>});</pre><p>This code ensures that connection errors are handled gracefully and attempts to reconnect if the connection is lost.</p><h4>Reconnection Strategies</h4><p>Socket.IO comes with built-in reconnection capabilities, but you can configure the number of reconnection attempts and delays.</p><pre>export const socketConnection = async (token) =&gt; {<br>  try {<br>    socket = io(process.env.NEXT_PUBLIC_API_SOCKET, {<br>      auth: {<br>        authorization: token,<br>      },<br>    reconnection: true,<br>    reconnectionAttempts: 5,<br>    reconnectionDelay: 3000,<br>    });<br>  } catch (error) {<br>    console.error(&#39;Error creating socket connection:&#39;, error);<br>  }<br>};</pre><h4>Namespaces for Better Organization</h4><p>If you want to segregate different types of communication (e.g., chat and notifications), namespaces can help you manage this easily.</p><pre>const chatSocket = io(&#39;http://your-server-url.com/chat&#39;);<br>const notificationSocket = io(&#39;http://your-server-url.com/notifications&#39;);</pre><p>Each namespace works independently, giving you more control over different communication channels.</p><h3>Conclusion</h3><p>With this guide, you now have the tools to effectively implement and manage socket listeners in both <strong>React.js</strong> and <strong>React Native</strong>. From creating connections to handling errors, security, and advanced features like namespaces and acknowledgments, you can build a robust and scalable real-time application.</p><p>Socket listeners provide the foundation for real-time interactivity, and with the tips in this blog, you’re ready to take your application to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=872be6e4798c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Action Buttons in Push Notifications using Firebase and Notifee]]></title>
            <link>https://medium.com/@hassem_mahboob/implementing-action-buttons-in-push-notifications-using-firebase-and-notifee-f5743bdb28bc?source=rss-1b9ee856676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5743bdb28bc</guid>
            <category><![CDATA[notifee-action-buttons]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[action-buttons-in-push]]></category>
            <category><![CDATA[push-notification-actions]]></category>
            <category><![CDATA[action-button]]></category>
            <dc:creator><![CDATA[Hassem Mahboob]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 10:06:25 GMT</pubDate>
            <atom:updated>2024-07-29T10:06:25.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EfNqOzWrTg-ldNotlJJHA.jpeg" /></figure><p>In this article, we will explore how to enhance the user experience by adding action buttons to push notifications. We’ll utilize Firebase for data-only push notifications and Notifee for handling the local notifications and their action buttons. By the end of this tutorial, you’ll be able to implement a robust notification system that supports actions even when the app is in the background or killed.</p><p><strong>Install Required Packages:</strong></p><pre>npm install @react-native-firebase/app @react-native-firebase/messaging @notifee/react-native</pre><p>Before proceeding with the steps in this article, ensure that you have established a connection between Firebase and your app. This setup is crucial for receiving notifications. You can refer to other articles or official documentation for guidance on integrating Firebase with your app. This article focuses on handling notifications and does not cover the Firebase connection setup.</p><h3>1. Understanding Data-Only Notifications</h3><p>Data-only notifications are push notifications that carry a payload of data but do not display any notification to the user by default. These notifications are particularly useful when you want to handle the display logic within the app, offering more flexibility and control.</p><p><strong>Key Points:</strong></p><ul><li>They are received in the background, allowing you to process data silently.</li><li>Perfect for scenarios where you want to update your app’s UI or perform background tasks without interrupting the user.</li></ul><h3>2. Firebase Listeners for All Cases</h3><p>To handle data-only notifications effectively, you need to implement Firebase listeners for different app states: killed, background, and foreground.</p><p><strong>Foreground:</strong></p><pre>import messaging from &#39;@react-native-firebase/messaging&#39;;<br><br>messaging().onMessage(async remoteMessage =&gt; {<br>  console.log(&#39;A new FCM message arrived!&#39;, remoteMessage);<br>  // Handle the data-only notification<br>  // based on your notifications you can trigger the local notifcation with action using this function that is mentioned below <br>  await displayLocalNotification(remoteMessage);<br>});</pre><p><strong>Background:</strong></p><pre>import messaging from &#39;@react-native-firebase/messaging&#39;;<br><br>messaging().setBackgroundMessageHandler(async remoteMessage =&gt; {<br>  console.log(&#39;Message handled in the background!&#39;, remoteMessage);<br>  // Handle the data-only notification<br>});</pre><p><strong>Killed:</strong></p><p>To ensure that your app handles notifications correctly even when it’s in the killed state, you need to set up the Firebase listeners in the entry point of your application. This is typically done in the index.js or App.jsfile. If these listeners are not added at the start, your app will not be able to process notifications when it is not running.</p><p><strong>Why is this important?</strong> When the app is killed, it is not running in the background, and thus, typical listeners defined in components or other parts of the app will not be active. By placing these listeners in index.js, they are registered as soon as the app starts, allowing it to handle notifications immediately, regardless of the app&#39;s state.</p><pre><br>import messaging from &#39;@react-native-firebase/messaging&#39;;<br><br>messaging().setBackgroundMessageHandler(async remoteMessage =&gt; { <br>console.log(&#39;Message handled in the kill state!&#39;, remoteMessage);<br>  // Handle the data-only notification<br>});</pre><h3>3. Introduction to Notifee</h3><p>Notifee is a powerful library for managing notifications in React Native applications. It offers extensive features for creating, displaying, and handling notifications, including the addition of action buttons.</p><p><strong>Key Features:</strong></p><ul><li>Customizable notifications with rich media.</li><li>Support for action buttons.</li><li>Integration with Firebase for advanced notification handling.</li><li>Listeners for notification clicks and interactions.</li></ul><h3><strong>Display Local Notification Function:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*yhGpYH6A5UjyOrq2T1r24w.png" /></figure><p>Create a function to display a local notification using Notifee with action buttons when a Firebase message is detected.</p><pre>import notifee, { AndroidImportance } from &#39;@notifee/react-native&#39;;<br><br>async function displayLocalNotification(remoteMessage) {<br>  // Create a channel (required for Android)<br>  const channelId = await notifee.createChannel({<br>    id: &#39;default&#39;,<br>    name: &#39;Default Channel&#39;,<br>    importance: AndroidImportance.HIGH,<br>  });<br><br>  // Display a notification<br>  await notifee.displayNotification({<br>    title: remoteMessage.data.title,<br>    body: remoteMessage.data.body,<br>    android: {<br>      channelId,<br>      actions: [<br>        {<br>          title: &#39;Action 1&#39;,<br>          pressAction: { id: &#39;action-1&#39; },<br>        },<br>        {<br>          title: &#39;Action 2&#39;,<br>          pressAction: { id: &#39;action-2&#39; },<br>        },<br>      ],<br>    },<br>  });<br>}</pre><h3>4. Notifee Listeners for Click Detection</h3><p>To handle the actions when a notification button is clicked, you need to set up Notifee listeners.</p><pre>import notifee, { EventType } from &#39;@notifee/react-native&#39;;<br><br>notifee.onForegroundEvent(({ type, detail }) =&gt; {<br>  switch (type) {<br>    case EventType.ACTION_PRESS:<br>      console.log(&#39;User pressed an action with ID: &#39;, detail.pressAction.id);<br>      // Perform the appropriate action based on the action ID<br>      if (detail.pressAction.id === &#39;action-1&#39;) {<br>        // Handle Action 1<br>      } else if (detail.pressAction.id === &#39;action-2&#39;) {<br>        // Handle Action 2<br>      }<br>      break;<br>    case EventType.DISMISSED:<br>      console.log(&#39;Notification was dismissed by the user&#39;);<br>      break;<br>  }<br>});</pre><p><strong>Handling Notification Clicks in Background and Killed States:</strong></p><pre>import notifee from &#39;@notifee/react-native&#39;;<br><br>notifee.onBackgroundEvent(async ({ type, detail }) =&gt; {<br>  const { notification, pressAction } = detail;<br>  if (type === EventType.ACTION_PRESS &amp;&amp; pressAction.id) {<br>    console.log(&#39;User pressed an action in the background with ID: &#39;, pressAction.id);<br>    // Perform the appropriate action based on the action ID<br>    if (pressAction.id === &#39;action-1&#39;) {<br>      // Handle Action 1<br>    } else if (pressAction.id === &#39;action-2&#39;) {<br>      // Handle Action 2<br>    }<br>  }<br>});</pre><h3>Conclusion</h3><p>By combining Firebase data-only notifications with Notifee’s robust notification handling features, you can create a seamless and interactive user experience. This approach ensures that your app can respond to user actions in notifications, regardless of the app’s state.</p><p>Feel free to adapt and expand on these snippets to suit your specific use case and requirements. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5743bdb28bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Enable Push Notifications with Images in a React Native iOS Project & app icon badge count…]]></title>
            <link>https://medium.com/@hassem_mahboob/how-to-add-images-and-app-icon-badge-count-in-react-native-node-js-6c0f58dded57?source=rss-1b9ee856676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0f58dded57</guid>
            <category><![CDATA[images-innotification-ios]]></category>
            <category><![CDATA[react-native-badge]]></category>
            <category><![CDATA[react-native-push-notfctn]]></category>
            <dc:creator><![CDATA[Hassem Mahboob]]></dc:creator>
            <pubDate>Tue, 28 May 2024 06:32:00 GMT</pubDate>
            <atom:updated>2026-09-29T11:24:26.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Enable Push Notifications with Images in a React Native iOS Project &amp; app icon badge count in react native/ node.js?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*ZXF0xBS9zAYlY7h4eD4N0A.png" /></figure><p>In today’s competitive app landscape, user engagement is more crucial than ever. Push notifications play a pivotal role in keeping users engaged and informed. Enhancing these notifications with images and app icon badge counts can significantly improve user interaction and retention.</p><p>This article will guide you through the process of adding images to push notifications and managing app icon badge counts in a React Native application, using Node.js as the backend. Whether you’re looking to create more visually appealing notifications or ensure accurate badge counts, these steps will help you achieve your goals efficiently and effectively.</p><h3>Handling App Icon Badge Count</h3><h4><strong>Frontend (Mobile Side) Handling</strong></h4><p>H<strong>andling </strong>badge counts on the frontend is straightforward but not always reliable. Here’s how you can do it:</p><h4><strong>Setup React Native Project</strong></h4><p>Before we dive into adding images and managing app icon badge counts in push notifications, let’s start by setting up a React Native project. This foundational step ensures you have all the necessary tools and configurations in place to implement the enhancements effectively.</p><pre>npx react-native init YourProjectName<br>cd YourProjectName</pre><h4>Install Required Packages</h4><pre>npm install react-native-push-notification</pre><p>Link the Package For React Native &gt;= 0.60, auto-linking is enabled, so this step is not needed.</p><h4><strong>Set Badge Count on Frontend</strong></h4><pre>import PushNotification from &#39;react-native-push-notification&#39;;<br><br>PushNotification.setApplicationIconBadgeNumber(5);  // Example to set the badge count to 5<br><br>// to detect the push notification and set the notification badge you can follow the below code <br><br>messaging().setBackgroundMessageHandler(async remoteMessage =&gt; {<br> <br> PushNotificationIOS.setApplicationIconBadgeNumber(1);<br><br> });</pre><h4>Backend (Server Side) Handling</h4><pre>const admin = require(&quot;firebase-admin&quot;);<br>admin.initializeApp({<br>credential: admin.credential.cert(firebaseConfig),<br>databaseURL: &quot;https://your-app-name-default-rtdb.firebaseio.com&quot;,<br>});<br>message = {<br>      notification: { body, title },<br>      data: {<br>        content_available: &quot;true&quot;,<br>        priority: &quot;normal&quot;,<br>        title: &quot;New message&quot;<br>      },<br>      apns: {<br>        payload: {<br>          aps: {<br>            badge : 10<br>          }<br>        },<br>        headers:{<br>          &quot;apns-priority&quot;:&quot;5&quot; // to send notification on priority<br>        },<br>        fcm_options: {<br>          image: &quot;https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg&quot;<br>        }<br>      },<br>      token: userTocken,<br>    };</pre><h3>How to Enable Push Notifications with Images in a React Native iOS Project</h3><h3><strong>iOS setup</strong></h3><h4><strong>1. Create a Notification Service Extension</strong></h4><p>Within your project, you must create a Service Extension. A Service Extension allows for the modification of a notification to include rich media. To add a notification service extension, click on <strong>File &gt; New &gt; Target and select Notification Service Extension</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDqDSQocWylAi-fS77p98Q.png" /></figure><p><strong>2. Setting up Notification Service Extension</strong></p><p>Since the Notification Service Extension has its own bundle id, it must be set up with its own App ID and provisioning profile. Please verify through the Apple Developer Service.</p><pre><br>//  NotificationService.m<br>//  ImageNotification<br><br>#import &quot;NotificationService.h&quot;<br>#import  &quot;FirebaseMessaging.h&quot;<br><br><br><br>@interface NotificationService ()<br><br>@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);<br>@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;<br><br>@end<br><br>@implementation NotificationService<br><br>- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {<br>    self.contentHandler = contentHandler;<br>    self.bestAttemptContent = [request.content mutableCopy];<br>    <br>    // Modify the notification content here...<br>   [[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent withContentHandler:contentHandler];<br><br>}<br><br>- (void)serviceExtensionTimeWillExpire {<br>    // Called just before the extension will be terminated by the system.<br>    // Use this as an opportunity to deliver your &quot;best attempt&quot; at modified content, otherwise the original push payload will be used.<br>    self.contentHandler(self.bestAttemptContent);<br>}<br><br>@end</pre><p>Now, perform a clean build and restart the app, then send the push notification with images as previously described.</p><p>If you enjoyed this Medium article, please feel free to like, <a href="https://medium.com/@hassem_mahboob"><strong>share</strong></a>, and subscribe! Your support is greatly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0f58dded57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>