DEV Community

shyam manek
shyam manek

Posted on

4 1

React Native App using Realm Database

** Create a Database Schema

**
*Folder ./Db/Schema.js
*

export const TodosSchema = {
    name:'Todos',
    properties:{
        _id:'string',
        title:'string',
        completed:'bool'
    },
    primaryKey:'_id'
}

Enter fullscreen mode Exit fullscreen mode

App.js

import React, {useEffect, useState} from 'react';
import {Button,ScrollView,StyleSheet,Text,View} from 'react-native';

import Realm from 'realm';
import {TodosSchema} from './db/schema';
import {nanoid} from '@reduxjs/toolkit';

Enter fullscreen mode Exit fullscreen mode

Declareations States

let realm;

const App = () => {
const [data, setData] = useState([]);


Enter fullscreen mode Exit fullscreen mode

create realm instance on app launch

 useEffect(() => {
    const getRealmInstance = async () => {
      try {
        realm = await Realm.open({
          path: 'myrealm',
          schema: [TodosSchema],
        });
      } catch (e) {
        console.log(e);
      }
    };
      let todos = realm.objects('Todos');
      setData([...todos]);
    getRealmInstance();
  }, []);

Enter fullscreen mode Exit fullscreen mode

//CREATE DATA In Object

  const createData = () => {
    realm.write(() => {
      realm.create('Todos', {
        _id: nanoid(),
        title: 'this is ui',
        completed: true,
      });

    });   

Enter fullscreen mode Exit fullscreen mode

** Single Read**

let  item =realm.objectForPrimaryKey('Todos','id');
console.log(item)
Enter fullscreen mode Exit fullscreen mode

**UPDATE DATA

**

const UpdateData = id => {
    realm.write(() => {
      let data = realm.objectForPrimaryKey('Todos', id);
      // data.title = 'SDM';
      data.completed = true
      // console.log(data._id)
      console.log(data);
      // realm.delete(data)

    });

  };

Enter fullscreen mode Exit fullscreen mode

DELETE Function

const (DeleteTodo)= id => {
    realm.write(() => {
      let deletedata = realm.objectForPrimaryKey('Todos', id);
      realm.delete(deletedata);
    });

  };`

Enter fullscreen mode Exit fullscreen mode

return (
<View>
<TextInput style={styles.input}  placeholder="title " />
<Button onPress={createData} title="Add Tasks..." />

<ScrollView>
{data.map(item => (
<View key={nanoid()}>
   <Text>{item.title} , {String(item.completed)}</Text>
   <Text>{item._id}</Text>
<View>
   <Button onPress={UpdateData(item._id)} title="Edit" />
   <Button onPress={DeleteTodo(item._id)} title="Delete" />
</View>
</View>
))}
</ScrollView>
 </View>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode

const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
},
});




Package.josn

**Dependencies**

`"dependencies": {
    "@reduxjs/toolkit": "^1.7.1",
    "react": "17.0.2",
    "react-native": "0.66.4",
    "react-redux": "^7.2.6",
    "realm": "^10.11.0",
    "redux": "^4.1.2"
  },
`

`
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay