shemonti barua
shemonti barua

Reputation: 11

Error fetching data [TypeError: Cannot read property 'rows' of undefined] in react native using expo sql lite

this is database.js

import * as SQLite from 'expo-sqlite/legacy';

const database_name = "AppDatabase.db";
const database_version = "1.0";
const database_displayname = "SQLite Test Database";
const database_size = 200000;

const initDB = async () => {
  try {
    const db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size);
    console.log("Database opened");
    return db;
  } catch (error) {
    console.error("Error: ", error);
    throw error;
  }
};

const executeQuery = async (db, sql, params = []) => {
  try {
    const result = await db.transactionAsync(async tx => {
      const res = await tx.executeSqlAsync(sql, params);
      return res;
    });
    return result;
  } catch (error) {
    console.error("SQL Error: ", error);
    throw error;
  }
};

export { initDB, executeQuery };

then i use that database.js in columninfoscreen.js

import React, { useEffect, useState } from 'react';
import { View, Text, ScrollView, StyleSheet, Alert } from 'react-native';
import { fetchData } from '../../Config'; // Adjust the import path as needed
import { initDB, executeQuery } from '../components/dtbase'; // Adjust the import path as needed

const ColumnInfoScreen = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const loadData = async () => {
      try {
        const db = await initDB();
        console.log("Database initialized");

        // Create table if it doesn't exist
        await executeQuery(db, `CREATE TABLE IF NOT EXISTS posts (
          userId INTEGER,
          id INTEGER PRIMARY KEY,
          title TEXT,
          body TEXT
        )`, []);
        console.log('executionqury is successfull')

        // Fetch data from API
        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const postsData = await response.json();
        // console.log(postsData);

        // Insert fetched data into the SQLite table
        for (let post of postsData) {
       
          await executeQuery(db, `INSERT OR REPLACE INTO posts (
            userId, id, title, body
          ) VALUES (?, ?, ?, ?)`, [
            post.userId,
            post.id,
            post.title || '',
            post.body || ''
          ]);
        }
        console.log('insertion is successfull');

        // Retrieve data from SQLite table
        const results = await executeQuery(db, `SELECT id FROM posts`, []);
        console.log(results)

        const storedPosts = [];
        for (let i = 0; i < results.rows.length; i++) {
          
          storedPosts.push(results.rows.item(i));
        }
        setPosts(storedPosts);
        console.log("Data retrieved from SQLite table");

      } catch (error) {
        console.log('Error fetching data', error);
      }
    };

    loadData();
  }, []);

  return (
    <ScrollView style={styles.container}>
      {posts.map((post, index) => (
        <View key={index} style={styles.postContainer}>
          <Text style={styles.title}>{post.title}</Text>
          <Text style={styles.body}>{post.body}</Text>
        </View>
      ))}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  postContainer: {
    marginBottom: 15,
  },
  title: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  body: {
    fontSize: 14,
    color: '#666',
  },
});

export default ColumnInfoScreen;

when i run the code i got Database opened LOG Database initialized LOG executionqury is successfull LOG insertion is successfull LOG undefined LOG Error fetching data [TypeError: Cannot read property 'rows' of undefined] in results it shows undefined..please give me solution

I tried using promise based run but failed

Upvotes: 0

Views: 36

Answers (0)

Related Questions