How to use SQLite in React Native

How to use SQLite in React Native

ยท

3 min read

The purpose of writing this blog is to give a simple explanation of SQLite in React Native, and how you can implement it.

  • Setting up SQLite in our project

  • Creating ProductsDB file

  • Using ProductsDB file

  • Conclusion

Setting up SQLite in our project

To install SQLite, run the following code in your terminal:

npm install --save react-native-sqlite-storage

Creating our ProductsDB file

Now, let's create a file where we'll do all of our SQLite operations and use it.

import { openDatabase, enablePromise } from 'react-native-sqlite-storage';

enablePromise(true);
let db;

export const openDBConnection = async () => {
  db = await openDatabase({ name: 'ProductsDB.db' });
};

export const createTable = async () => {
  try {
    const query = `CREATE TABLE IF NOT EXISTS Products(
                name TEXT NOT NULL, price INTEGER NOT NULL
            );`;
    await db.executeSql(query);
  } catch (error) {
    console.log('Table Creation Unsuccessful');
  }
};

export const fetchProducts = async () => {
  try {
    let resultsSet = [];
    let query = `SELECT * FROM Products`;
    const res = await db.executeSql(query);
    for (let i = 0; i < res[0].rows.length; ++i) {
      let record = res[0].rows.item(i);
      resultsSet.push(record);
    }
    return resultsSet;
  } catch (error) {
    console.log('ERROR: GetProducts');
  }
};

export const addProduct = async (product) => {
  try {
    const { name, price } = product;
    let query = `INSERT INTO Products(name, price) VALUES('${name}',${price})`;
    await db.executeSql(query);
  } catch (error) {
    console.log('ERROR: Save Product DB');
  }
};

export const deleteProduct = async (id) => {
  try {
    const deleteQuery = `DELETE FROM Products WHERE rowid = ${id}`;
    await db.executeSql(deleteQuery);
  } catch (error) {
    console.log('ERROR: Deleting Product');
  }
};

export const deleteTable = async () => {
  try {
    const query = `DROP TABLE Products`;
    await db.executeSql(query);
  } catch (error) {
    console.log('ERROR: Deleting Table');
  }
};

You can also create multiple DB files like this such as UsersDB, EmployeesDB, CoursesDB etc.

Using our ProductsDB file

As I'm using Stack Navigation, so we have to use this in our Home.js file. And to use it, we must store some entries in it. Run the code below 3โ€“4 times with different objects.

import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, FlatList} from 'react-native';
import {
  openDBConnection,
  createTable,
  fetchProducts,
} from '../database/ProductsDB';

const Home = () => {
  const [products, setProducts] = useState();
  useEffect(() => {
    InitialSetup();
  }, []);

  const InitialSetup = async () => {
    try {
      await getDBConnection();
      await createTable();
      await addProduct({ name: 'Keychain', price: 10 });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <Text>Home</Text>
      <FlatList
        data={products}
        keyExtractor={(item, index) => index}
        renderItem={({item}) => (
          <View>
            <Text>{item.name}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default Home;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

The dummy data will now be saved to the database, now let's look at how we can use it to get all the data from the database

import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, FlatList} from 'react-native';
import {
  openDBConnection,
  createTable,
  fetchProducts,
} from '../database/ProductsDB';

const Home = () => {
  const [products, setProducts] = useState();
  useEffect(() => {
    InitialSetup();
  }, []);

  const InitialSetup = async () => {
    try {
      await openDBConnection();
      await createTable();
      const storedProducts = await fetchProducts();
      setProducts(storedProducts);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <Text>Home</Text>
      <FlatList
        data={products}
        keyExtractor={(item, index) => index}
        renderItem={({item}) => (
          <View>
            <Text>{item.name}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default Home;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

Conclusion

This way, you can use SQLite without the hassle of making your code look bloated. Soon, I'm going to write another blog where I'll demonstrate an app which will do all of these SQLite operations.

ย