npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

expo-sqlite-reactive

v0.0.1

Published

A reactive wrapper for expo-sqlite that enables reactivity in database operations with event-driven updates.

Downloads

64

Readme

alt text

Documetación en español

Ver acá

expo-sqlite-reactive

expo-sqlite-reactive is a solution that extends the functionality of expo-sqlite to provide a reactive way to work with SQLite databases in Expo and React Native applications. This package allows you to create tables, perform CRUD operations, and keep your UI in sync with data changes using the useQuery hook.

Features

  • Reactivity: Use useQuery to listen for changes and automatically update the UI when the database changes.
  • CRUD Support: Simple methods for creating, reading, updating, and deleting data.
  • SQLite-Based: Leverages the robustness of expo-sqlite for local storage.
  • Simplicity: Provides an intuitive and straightforward interface.

Installation

npm install expo-sqlite-reactive

Make sure expo-sqlite is installed as a dependency.

expo install expo-sqlite

Basic Usage

1. Database Initialization

First, initialize the database with your desired name:

import { SQLiteManager } from 'expo-sqlite-reactive';

async function initializeDB() {
  try {
    SQLiteManager.initialize('mydatabase.db');

    await SQLiteManager.createTable('users', {
      usersUUID: 'text',
      firstName: 'text',
      lastName: 'text',
      email: 'text',
      password: 'text',
    });
  } catch (error) {
    console.error('Error initializing database:', error);
  }
}

2. Creating Tables

await SQLiteManager.createTable('products', {
  productUUID: 'text',
  productName: 'text',
  productPrice: 'integer',
});

3. Inserting Data

const product = {
  productUUID: '1234',
  productName: 'Laptop',
  productPrice: 999,
};

await SQLiteManager.insert('products', product);

4. Querying Data with useQuery

useQuery provides a reactive way to query and update the UI when data changes.

import { useQuery } from 'expo-sqlite-reactive';

export default function ProductList() {
  // Reactive query on the "products" table
  const [products, error] = useQuery('products', ['*'], undefined, { productName: 1 });

  if (error) return <Text>Error loading products</Text>;

  return (
    <View>
      {products.map((product) => (
        <Text key={product.productUUID}>{product.productName} - ${product.productPrice}</Text>
      ))}
    </View>
  );
}

useQuery Parameters

const [data, error] = useQuery(
  tableName: string,          // Name of the table to query
  columns: string[],          // Columns to select (e.g., ['*'] to select all)
  whereClause?: object,       // Optional filtering conditions (e.g., { price: { $gt: 50 } })
  sort?: { [key: string]: 1 | -1 } // Sorting (e.g., { price: 1 } for ascending order by price)
);
  • tableName: The name of the table to query.
  • columns: An array of strings specifying which columns to select. ['*'] selects all columns.
  • whereClause: An optional object defining filtering conditions, similar to MongoDB queries.
  • sort: An optional object defining the order of results (1 for ascending, -1 for descending).

5. Deleting and Updating Data

Dropping a table:

await SQLiteManager.dropTable('products');

Updating a record:

await SQLiteManager.update('products', { productUUID: '1234' }, { productPrice: 899 });

Deleting a record:

await SQLiteManager.delete('products', { productUUID: '1234' });

Examples of Complex Queries

Query with Conditions

const [products, error] = useQuery(
  'products',
  ['productName', 'productPrice'],
  { productPrice: { $gt: 100 } }, // Condition: prices greater than 100
  { productName: 1 }              // Ascending order by product name
);

Inserting and Querying Data

// Insert a new user
await SQLiteManager.insert('users', {
  usersUUID: '1234',
  firstName: 'John',
  lastName: 'Doe',
  email: '[email protected]',
  password: 'password123',
});

// Query all users
const [users, error] = useQuery('users', ['*']);

Comparison with Realm

expo-sqlite-reactive can be considered a lightweight and efficient alternative to Realm in certain scenarios:

  • Reactive Synchronization: useQuery provides a reactive way to update the UI, similar to Realm's reactive collections.
  • Simplicity: While Realm offers many advanced features, expo-sqlite-reactive is simpler and designed for scenarios where complex synchronization or heavy databases are not required.
  • Native Support: Being based on SQLite, it leverages a backend that is common across many systems and devices, offering potential performance and compatibility advantages.

Full Example

import React from 'react';
import { View, Text, Button } from 'react-native';
import { SQLiteManager, useQuery } from 'expo-sqlite-reactive';
import * as uuid from 'uuid';

export default function App() {
  const [stores, error] = useQuery('stores', ['*'], undefined, { added: -1 });

  async function createStores() {
    for (let i = 0; i < 5; i++) {
      const store = {
        storesUUID: uuid.v4(),
        storeName: `Store ${i}`,
        storeAddress: `Address ${i}`,
      };
      await SQLiteManager.insert('stores', store);
    }
  }

  return (
    <View>
      <Button title="Create Stores" onPress={createStores} />
      {error && <Text>Error loading stores: {error.message}</Text>}
      {stores.map((store) => (
        <Text key={store.storesUUID}>
          {store.storeName} - {store.storeAddress}
        </Text>
      ))}
    </View>
  );
}

About the Author

This library was developed by César Casas / Stock42.

alt text

License

MIT License. See the LICENSE file for more details.