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();
// 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
)`, []);
// Fetch data from API
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const postsData = await response.json();
// 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 || ''
]);
}
// Retrieve data from SQLite table
const results = await executeQuery(db, 'SELECT * FROM posts', []);
const storedPosts = [];
for (let i = 0; i < results.rows.length; i++) {
storedPosts.push(results.rows.item(i));
}
setPosts(storedPosts);
} 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 this screen shows
Error fetching data [TypeError: Cannot convert null value to object].I want to fetch api and store it into sqllite database storage and then want to show data from database table.but above code does not work.It shows me error
I tried many solution available in goggle but failed