<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pradeep</title>
    <description>The latest articles on DEV Community by Pradeep (@deepbb).</description>
    <link>https://dev.to/deepbb</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F618605%2F525c3011-aacd-43e2-b850-4452d8a8fe0f.jpg</url>
      <title>DEV Community: Pradeep</title>
      <link>https://dev.to/deepbb</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/deepbb"/>
    <language>en</language>
    <item>
      <title>How to Implement Push Notifications in React Native for Android and iOS</title>
      <dc:creator>Pradeep</dc:creator>
      <pubDate>Sun, 22 Dec 2024 13:19:29 +0000</pubDate>
      <link>https://dev.to/deepbb/how-to-implement-push-notifications-in-react-native-for-android-and-ios-50fp</link>
      <guid>https://dev.to/deepbb/how-to-implement-push-notifications-in-react-native-for-android-and-ios-50fp</guid>
      <description>&lt;p&gt;Push notifications are a crucial feature in modern mobile applications, enabling real-time communication with users. In this article, I'll guide you through implementing push notifications in a React Native app for both Android and iOS. We'll cover setting up the notification prompt and managing permissions, along with code examples.&lt;/p&gt;

&lt;p&gt;Why Push Notifications?&lt;/p&gt;

&lt;p&gt;Push notifications allow you to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1. - Engage users with timely updates.&lt;/li&gt;
&lt;li&gt;2. - Increase user retention through reminders.&lt;/li&gt;
&lt;li&gt;3. - Notify users about important events, offers, or updates.&lt;/li&gt;
&lt;li&gt;4. - Let’s dive into implementing this in React Native.
Setting Up Push Notifications&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Prerequisites
Before starting, ensure you have:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A React Native app set up.&lt;br&gt;
Dependencies installed:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;@react-native-async-storage/async-storage&lt;/li&gt;
&lt;li&gt;react-native-push-notification&lt;/li&gt;
&lt;li&gt;&lt;p&gt;@react-native-firebase/messaging (if using Firebase for &lt;br&gt;
notifications)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Requesting Notification Permissions&lt;br&gt;
Permissions are critical for enabling push notifications. Here’s how to set up a prompt when a user clicks a button (e.g., "Remind Me") to request notification permissions.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Alert, PermissionsAndroid, Platform } from 'react-native';
import PushNotification from 'react-native-push-notification';

export async function requestNotificationPermission() {
  if (Platform.OS === 'ios') {
    // iOS-specific permission request
    const authStatus = await messaging().requestPermission();
    if (
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL
    ) {
      setupPushNotificationChannel();
    } else {
      Alert.alert('Permission Denied', 'Notifications are disabled.');
    }
  } else if (Platform.OS === 'android') {
    // Android-specific permission request
    if (Platform.Version &amp;gt;= 33) {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
          {
            title: 'Notification Permission',
            message: 'Allow this app to send notifications?',
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          setupPushNotificationChannel();
        } else {
          Alert.alert(
            'Permission Denied',
            'Please enable notifications from settings.'
          );
        }
      } catch (error) {
        console.error('Permission request failed:', error);
      }
    } else {
      setupPushNotificationChannel();
    }
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;Setting Up Notification Channels
Notification channels are essential on Android to categorize and prioritize notifications. The following code demonstrates how to create a channel using react-native-push-notification:
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const setupPushNotificationChannel = () =&amp;gt; {
  PushNotification.createChannel(
    {
      channelId: 'default_channel', // Unique ID for the channel
      channelName: 'Default Notifications', // Channel name
      channelDescription: 'A default notification channel', // Description
      vibrate: true, // Vibration setting
    },
    (created) =&amp;gt; console.log(`Notification channel created: ${created}`)
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;Triggering Local Notifications
You can trigger a local notification using react-native-push-notification. This is useful for testing or sending reminders.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const triggerLocalNotification = () =&amp;gt; {
  PushNotification.localNotification({
    channelId: 'default_channel',
    title: 'Reminder!',
    message: 'Don’t forget to check this out!',
    playSound: true,
    soundName: 'default',
    vibrate: true,
  });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;Handling Notifications in Foreground, Background, and Quit States
To manage notification behavior in different app states, you can use @react-native-firebase/messaging or a similar package.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import messaging from '@react-native-firebase/messaging';

export const notificationListener = () =&amp;gt; {
  // Handle notification when the app is in the foreground
  messaging().onMessage(async (remoteMessage) =&amp;gt; {
    console.log('Foreground notification:', remoteMessage);
    triggerLocalNotification();
  });

  // Handle notification when the app is opened from the background
  messaging().onNotificationOpenedApp((remoteMessage) =&amp;gt; {
    console.log('Notification opened:', remoteMessage);
  });

  // Handle notification when the app is launched via a notification
  messaging()
    .getInitialNotification()
    .then((remoteMessage) =&amp;gt; {
      if (remoteMessage) {
        console.log('Initial notification:', remoteMessage);
      }
    });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Final Implementation in Your App&lt;/p&gt;

&lt;p&gt;Integrate the above functions into your app. Here’s how you can wire everything together:&lt;/p&gt;

&lt;p&gt;Request permission when the user clicks a button:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Button title="Remind Me" onPress={requestNotificationPermission} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Trigger local notifications:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Button title="Test Notification" onPress={triggerLocalNotification}/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Initialize listeners in your app entry point:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { notificationListener } from './NotificationService';

useEffect(() =&amp;gt; {
  notificationListener();
}, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Impact of Push Notifications&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implementing push notifications can significantly enhance user engagement. Here are some key benefits:&lt;/p&gt;

&lt;p&gt;Real-time updates: Notify users about important events immediately.&lt;br&gt;
Improved retention: Send reminders to encourage users to return to the app.&lt;br&gt;
Enhanced experience: Personalise messages to create a tailored experience.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Firebase Crashlytics : Integration in React Native App</title>
      <dc:creator>Pradeep</dc:creator>
      <pubDate>Thu, 20 Jun 2024 07:50:47 +0000</pubDate>
      <link>https://dev.to/deepbb/firebase-crashlytics-integration-in-react-native-app-2p1b</link>
      <guid>https://dev.to/deepbb/firebase-crashlytics-integration-in-react-native-app-2p1b</guid>
      <description>&lt;p&gt;Crashlytics is one of the powerful tool from the Firebase that helps us to track and analyze the crashes in real-time, by enabling the Crashlytics in your App you can determine the root cause of the crash and you can understand the impact on your users hence you can keep your app stable authentic.&lt;br&gt;
In this article you can check the steps for configuration and the sample code to test the crash in real-time&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting Up Crashlytics in Your React Native App&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;Step 1 : Install Firebase SDK&lt;/em&gt;&lt;br&gt;
&lt;code&gt;npm install @react-native-firebase/app&lt;br&gt;
npm install @react-native-firebase/crashlytics&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Step 2 : Setup Firebase Project&lt;/em&gt; &lt;br&gt;
Next, you need to go to firebase console and create a new project and follow the instructions to generate a google-services.json file for Android or a GoogleService-Info.plist file for iOS.&lt;br&gt;
if you have already has a project running in firebase you can just download the google-services.json for Android and GoogleService-Info.plist for iOS&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Step 3: Integrate Crashlytics in your app&lt;/em&gt;&lt;br&gt;
This is one of the important and exciting part of integration&lt;br&gt;
copy the google-services.json fie you downloaded in firebase to the following path &lt;br&gt;
&lt;strong&gt;/android/app/.&lt;/strong&gt;&lt;br&gt;
Next open &lt;strong&gt;android/build.gradle&lt;/strong&gt; file and add the following dependency:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;// ..&lt;br&gt;
buildscript {&lt;br&gt;
  // ..&lt;br&gt;
  dependencies {&lt;br&gt;
    // ..&lt;br&gt;
    classpath 'com.google.firebase:firebase-crashlytics-gradle:3.0.0'&lt;br&gt;
  }&lt;br&gt;
  // ..&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
Next open android/app/build.gradle file and add the following plugins &lt;/p&gt;

&lt;p&gt;&lt;code&gt;apply plugin: 'com.android.application'&lt;br&gt;
apply plugin: 'com.google.gms.google-services' // apply after this line&lt;br&gt;
apply plugin: 'com.google.firebase.crashlytics'&lt;br&gt;
// ..&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Step 4 : Add a file to the base folder of your project with the name firebase.json and copy the following content &lt;/p&gt;

&lt;p&gt;&lt;code&gt;{&lt;br&gt;
  "react-native": {&lt;br&gt;
    "crashlytics_debug_enabled": true&lt;br&gt;
  }&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Step 5 : Rebuild the project&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx react-native run-android&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Step 6 : Force a test crash&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Add the following code in your app : &lt;/p&gt;

&lt;p&gt;`import React, { useEffect } from 'react';&lt;br&gt;
import { View, Button } from 'react-native';&lt;br&gt;
import crashlytics from '@react-native-firebase/crashlytics';&lt;/p&gt;

&lt;p&gt;async function onSignIn(user) {&lt;br&gt;
  crashlytics().log('User signed in.');&lt;br&gt;
  await Promise.all([&lt;br&gt;
    crashlytics().setUserId(user.uid),&lt;br&gt;
    crashlytics().setAttribute('credits', String(user.credits)),&lt;br&gt;
    crashlytics().setAttributes({&lt;br&gt;
      role: 'admin',&lt;br&gt;
      followers: '13',&lt;br&gt;
      email: user.email,&lt;br&gt;
      username: user.username,&lt;br&gt;
    }),&lt;br&gt;
  ]);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export default function App() {&lt;br&gt;
  useEffect(() =&amp;gt; {&lt;br&gt;
    crashlytics().log('App mounted.');&lt;br&gt;
  }, []);&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;br&gt;
      
        title="Sign In"&lt;br&gt;
        onPress={() =&amp;gt;&lt;br&gt;
          onSignIn({&lt;br&gt;
            uid: 'Aa0Bb1Cc2Dd3Ee4Ff5Gg6Hh7Ii8Jj9',&lt;br&gt;
            username: 'Pradeep',&lt;br&gt;
            email: '&lt;a href="mailto:pradeep@example.com"&gt;pradeep@example.com&lt;/a&gt;',&lt;br&gt;
            credits: 42,&lt;br&gt;
          })&lt;br&gt;
        }&lt;br&gt;
      /&amp;gt;&lt;br&gt;
       crashlytics().crash()} /&amp;gt;&lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}`&lt;/p&gt;

&lt;p&gt;Happy Coding !!&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>firebase</category>
      <category>javascript</category>
      <category>debug</category>
    </item>
    <item>
      <title>Using SQLite in React Native: Installation and Usage Guide</title>
      <dc:creator>Pradeep</dc:creator>
      <pubDate>Wed, 01 May 2024 07:31:43 +0000</pubDate>
      <link>https://dev.to/deepbb/using-sqlite-in-react-native-installation-and-usage-guide-1dha</link>
      <guid>https://dev.to/deepbb/using-sqlite-in-react-native-installation-and-usage-guide-1dha</guid>
      <description>&lt;p&gt;SQLite is a popular relational database management system that provides a lightweight and self-contained solution for storing and managing data. In React Native development, SQLite can be a powerful tool for building offline-first applications, caching API responses, and managing local data storage.&lt;/p&gt;

&lt;p&gt;Installation&lt;br&gt;
To use SQLite in your React Native project, you'll need to install the react-native-sqlite-storage package. Follow these steps to get started:&lt;/p&gt;

&lt;p&gt;Install the Package: Run the following command in your project directory to install the react-native-sqlite-storage package:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;npm install react-native-sqlite-storage&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Link the Library (for React Native &amp;lt; 0.60): If you're using a React Native version less than 0.60, you need to link the native dependencies by running:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;react-native link react-native-sqlite-storage&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Getting Started&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now that you have SQLite installed in your project, you can start using it to manage local data storage, cache API responses, or implement other data management features. Here's a basic guide to get you started:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;- Initialize SQLite Database: Open or create a new SQLite database in your React Native application. You can use the react-native-sqlite-storage package to initialize and interact with the database.&lt;/li&gt;
&lt;li&gt;- Perform Database Operations :Perform CRUD (Create, Read, Update, Delete) operations on your SQLite database. You can execute SQL queries to insert, retrieve, update, or delete data from tables in the database.&lt;/li&gt;
&lt;li&gt;- Handle Errors and Edge Cases: Handle errors gracefully and consider edge cases such as database versioning, migrations, and transaction management. Proper error handling ensures the reliability and stability of your application.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's break down the steps page by page and file by file:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Database Setup (Database.js):
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import SQLite from 'react-native-sqlite-storage';

const db = SQLite.openDatabase(
  { name: 'mydatabase.db', location: 'default' },
  () =&amp;gt; { },
  error =&amp;gt; { console.error('Error opening database:', error); }
);

export default db;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;API Caching Functions (APIUtils.js):
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import db from './Database';

// Function to insert or update data in the cache
export const cacheResponse = (url, data) =&amp;gt; {
  const timestamp = Date.now();
  db.transaction(tx =&amp;gt; {
    tx.executeSql(
      'INSERT OR REPLACE INTO api_cache (url, data, timestamp) VALUES (?, ?, ?)',
      [url, JSON.stringify(data), timestamp],
      () =&amp;gt; console.log('Data cached successfully'),
      (_, error) =&amp;gt; console.error('Error caching data:', error)
    );
  });
};

// Function to retrieve data from the cache
export const getCachedResponse = (url, callback) =&amp;gt; {
  db.transaction(tx =&amp;gt; {
    tx.executeSql(
      'SELECT data FROM api_cache WHERE url = ?',
      [url],
      (_, { rows }) =&amp;gt; {
        if (rows.length &amp;gt; 0) {
          const data = JSON.parse(rows.item(0).data);
          callback(data);
        } else {
          callback(null);
        }
      },
      (_, error) =&amp;gt; console.error('Error retrieving cached data:', error)
    );
  });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;API Fetching and Caching (VideoPlay.js):
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { cacheResponse, getCachedResponse } from './APIUtils';

// Function to fetch API data, cache it, and return it
const fetchAPI = async url =&amp;gt; {
  try {
    const cachedData = await new Promise(resolve =&amp;gt; getCachedResponse(url, resolve));
    if (cachedData) {
      console.log('Data retrieved from cache:', cachedData);
      return cachedData;
    } else {
      const response = await fetch(url);
      const data = await response.json();
      cacheResponse(url, data);
      console.log('Data retrieved from API and cached:', data);
      return data;
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    return null;
  }
};

// Usage example:
const apiUrl = 'https://api.example.com/data';
fetchAPI(apiUrl);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Database Initialization (App.js):
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from 'react';
import db from './Database';

const App = () =&amp;gt; {
  useEffect(() =&amp;gt; {
    // Create a table to store cached API responses
    db.transaction(tx =&amp;gt; {
      tx.executeSql(
        'CREATE TABLE IF NOT EXISTS api_cache (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT UNIQUE, data TEXT, timestamp INTEGER)',
        [],
        () =&amp;gt; console.log('Table created successfully'),
        (_, error) =&amp;gt; console.error('Error creating table:', error)
      );
    });
  }, []);

  return (
    // Your app components and navigation here
  );
};

export default App;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Use Cases&lt;/strong&gt;&lt;br&gt;
SQLite can be used for a variety of purposes in React Native applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Offline Data Storage: Store application data locally on the device, allowing the application to function offline or in areas with poor network connectivity.&lt;/li&gt;
&lt;li&gt;Caching API Responses: Cache network requests and API responses to improve performance and reduce bandwidth usage. Cached data can be retrieved quickly without the need for repeated network requests.&lt;/li&gt;
&lt;li&gt;Persistent Data Storage: Persist user preferences, settings, or application state across sessions by storing data in the SQLite database.&lt;/li&gt;
&lt;li&gt;Data Synchronization: Synchronize local data with remote servers or other devices, ensuring consistency and integrity of the data across multiple sources.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
SQLite is a versatile and powerful tool for managing data in React Native applications. By integrating SQLite into your projects, you can leverage its capabilities for offline data storage, caching, and synchronization, enhancing the user experience and performance of your applications.&lt;/p&gt;

&lt;p&gt;In this guide, we covered the installation of SQLite in React Native, basic usage patterns, and common use cases for incorporating SQLite into your projects. With this knowledge, you're well-equipped to start using SQLite in your React Native applications and unlock its full potential for data management.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
