logo
logo
AI Products 
Leaderboard Community🔥 Earn points

How to Add Local Database in React Native

avatar
Expert App Devs
collect
0
collect
0
collect
6
How to Add Local Database in React Native

Introduction

Data is the most important part in any software or program. If a program or software is not that big in scope, data is stored in variables. But the main drawback of that is that storing data in variable data will be destroyed or reset to its first value when the program or software restarts. The database is a solution for that it saves data and after even restarting software we can fetch stored data.


There are many types of databases like relational databases, NoSQL databases, columnar databases, object-oriented databases, document databases, graph databases, etc.

In react native, we can use any of those databases based on the project’s requirements. There are many options to use databases in react native projects like Async Storage, SQLite, Realm, PouchDB, etc. In this article, we will use the most popular relational database SQLite.

Pre-requisites

  • Basic Knowledge of JavaScripts
  • Basic Knowledge of React Native
  • Familiarity with a package manager like npm or yarn
  • Node JS 12.x.x or above
  • Familiarity with code editor like VSCode or Atom

Step 1: Create New Project

npx react-native init AwesomeProject


Step 2: Install Necessary package

npm install react-native-sqlite-storage


Step 3: Creating Form For Input

import React, {useState} from ‘react’;

import {View, Text, TextInput, TouchableOpacity} from ‘react-native’;

import {addHobies} from ‘../helpers/sqlHelper’


const Form = () => {

let formData = []

const [name, setName] = useState(‘’);

const [hobby, setHobby] = useState(‘’);

const onSubmit = () => {

fromData.push({name: name, hobby: hobby});

addHobbies(formData);

}

return (

<View>

<View>

<TextInput

placeholderTextColor={colors.grey}

placeholder={“Name”}

onChangeText={(val) => setName(val)}

/>

<TextInput

placeholderTextColor={colors.grey}

placeholder={“Hobby”}

onChangeText={(val) => setHobby(val)}

/>

</View>

</View>

);

};


export default Form;

Step 4: Creating Helpers for Database

export const createTable = (db) => {

db.transaction(tnx => {

tnx.executeSql(

`CREATE TABLE IF NOT EXISTS hobbies (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), hobby VARCHAR(20))`,

[],

(sqlTnx, res) => {

console.log(‘Table Created Successfully’);

},

error => {

console.log(‘error on creating table: ‘ + error.message);

},

);

});

};

export const addHobies= (db, data) => {

if (!data) {

console.log(‘data not available’);

return false;

} else {

db.transaction(txn => {

for (let i = 0; i < ata.length; ++i)

txn.executeSql(

`INSERT INTO hobbies(name, hobby) VALUES (?, ?)`,

[

data[i].name,

data[i].hobby

],

(sqlTxn, res) => {

console.log(`${data[i].hobby} added successfully`);

},

error => {

console.log(‘error on adding hobby ‘ + error.message);

},

);

});

}

};

export const getLocalData = (db, setData) => {

db.transaction(txn => {

txn.executeSql(

`SELECT * FROM hobbies ORDER BY id DESC`,

[],

(sqlTnx, res) => {

console.log(‘data retrieved successfully’);

let len = res.rows.length;

if (len > 0) {

let result = [];

for (let i = 0; i < len; i++) {

const item = res.rows.item(i);

result.push({

id: item.id,

title: item.name,

rating: item.hobby

});

}

setData(result);

}

},

error => {

console.log(‘error in getting result: ‘, error.message);

},

);

});

};

export const deleteItem = (db, id) => {

let query = `DELETE * FROM hobbies WHERE id = ${id}`;

db.transaction(txn => {

txn.executeSql(

query,

[],

(sqlTnx, res) => {

console.log(‘item deleted successfully’);

},

error => {

console.log(‘error in getting restaurant: ‘, error.message);

},

);

});

}

Step 5: Assemble all in main file

import React, {useState, useEffect} from ‘react’;

import {View, Text, FlatList} from ‘react-native’;

import {getLocalData, createTable} from ‘../helpers/sqlHelper’

import Form from ‘./src/component/form’;

const App = () => {

const [data, setData] = useState(undefined);

useEffect(() => {

createTable();

setData(getLocalData());

}

},[])

return(

<Form />

{data && <FlatList

data = data

key = {(item) => item.id}

renderItem = {(item) => <View>

<Text>{item.name}</Text>

<Text>{item.hobby}</Text>

<View/>}

/>}

)

}

export default App;

collect
0
collect
0
collect
6
avatar
Expert App Devs