ReactNative Offline storage with Insert, Delete, Update, and Read the data for Product details in RealmDB
Realm is a popular mobile database that you can use for local storage in a React Native application.
Here’s an example of a React Native app that uses Realm to perform CRUD (Create, Read, Update, Delete) operations on product details:
Step 1: Install Realm
Install the Realm package in your React Native project:
npm install realm
Step 2: Set Up Realm Schema
Define your Realm schema in a file, e.g., ProductModel.js
:
// ProductModel.js
import Realm from 'realm';
class ProductModel extends Realm.Object {}
ProductModel.schema = {
name: 'Product',
properties: {
id: 'int',
name: 'string',
description: 'string',
price: 'double',
},
};
export default ProductModel;
Step 3: Create a Realm Service
Create a service file, e.g., RealmService.js
, to handle CRUD operations:
// RealmService.js
import Realm from 'realm';
import ProductModel from './ProductModel';
const realm = new Realm({ schema: [ProductModel] });
const RealmService = {
getAllProducts: () => realm.objects('Product'),
//Addition of Product
addProduct: (product) => {
realm.write(() => {
realm.create('Product', product);
});
},
//Update of Product
updateProduct: (id, updatedProduct) => {
const product = realm.objectForPrimaryKey('Product', id);
if (product) {
realm.write(() => {
Object.keys(updatedProduct).forEach((key) => {
product[key] = updatedProduct[key];
});
});
}
},
//Delete Product
deleteProduct: (id) => {
const product = realm.objectForPrimaryKey('Product', id);
if (product) {
realm.write(() => {
realm.delete(product);
});
}
},
};
export default RealmService;
Step 4: Create React Native Components
Create components to display and interact with the product data. For example, a ProductList.tsx
component:
// ProductList.js
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Button } from 'react-native';
import RealmService from './RealmService';
const ProductList = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchData = () => {
const allProducts = RealmService.getAllProducts();
setProducts(allProducts);
};
fetchData();
}, []);
const handleDelete = (id) => {
RealmService.deleteProduct(id);
const updatedProducts = RealmService.getAllProducts();
setProducts(updatedProducts);
};
return (
<View>
<FlatList
data={products}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
<Text>${item.price}</Text>
<Button title="Delete" onPress={() => handleDelete(item.id)} />
</View>
)}
/>
</View>
);
};
export default ProductList;
Step 5: Add, Update, and Delete Product
In another component or screen, you can implement forms to add, update, and delete products using RealmService
.