How to view react native application database with tables - sqlite

I'm creating a react native app. now I want to view my App database tables.
I don't know how many tables are in my SQLite database.
I am new in react native development & SQLite please help. to solve this issue

You can solve this problem through the Table View command. It can also be used to view data for that table.
/*Screen to view all the table*/
import React from 'react';
import { FlatList, Text, View } from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';
var db = openDatabase({ name: 'UserDatabase.db' });
export default class ViewAllTable extends React.Component {
constructor(props) {
super(props);
this.state = {
FlatListItems: [],
};
db.transaction(tx => {
tx.executeSql('SHOW TABLES', [], (tx, results) => {
var temp = [];
for (let i = 0; i < results.rows.length; ++i) {
temp.push(results.rows.item(i));
}
this.setState({
FlatListItems: temp,
});
});
});
}
ListViewItemSeparator = () => {
return (
<View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} />
);
};
render() {
return (
<View>
<FlatList
data={this.state.FlatListItems}
ItemSeparatorComponent={this.ListViewItemSeparator}
keyExtractor={(item, index) => index.toString()}
renderItem={({item, index }) => (
<View key={item[index]} style={{ backgroundColor: 'white', padding: 20 }}>
<Text>Table: {item[index]}</Text>
</View>
)}
/>
</View>
);
}
}

Related

How do I search for titles in Cloud Firestore using the SearchBar from react-native-elements?

I imported a SearchBar from react-native-elements and I want to be able to search my articles by title. So the field I should be able to pull and search from Cloud Firestore is called 'title'. I'm not sure how to do that.
import React, { Component } from "react";
import { StyleSheet, View, FlatList } from "react-native";
import { AppleCard } from "react-native-apple-card-views";
import firebase from "../../Firebase";
import { SearchBar } from 'react-native-elements';
import { ScrollView } from "react-native-gesture-handler";
export default class Discover extends Component {
constructor(props) {
super();
this.ref = firebase.firestore().collection("articles").where("publish", "==", true);
this.unsubscribe = null;
this.state = {
articles: [],
search: '',
};
}
onCollectionUpdate = (querySnapshot) => {
const articles = [];
querySnapshot.forEach((doc) => {
const { title, subtitle, imageUrlPath } = doc.data();
articles.push({
key: doc.id,
doc, // DocumentSnapshot
title,
subtitle,
imageUrlPath,
});
});
this.setState({
articles,
});
};
componentDidMount() {
this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
}
updateSearch = (search) => {
this.setState({ search });
};
renderItem = ({ item }) => {
return (
<View>
<View style={styles.card}>
<AppleCard
largeTitle={item.title}
smallTitle=""
footnoteText={item.subtitle}
resizeMode="cover"
source={{uri:item.imageUrlPath}}
onPress={() => {
this.props.navigation.navigate("Content", {
articlekey: `${JSON.stringify(item.key)}`,
});
}}
/>
</View>
</View>
);
};
render() {
const { search } = this.state;
return (
<ScrollView>
<SearchBar
placeholder="Search here..."
onChangeText={this.updateSearch}
value={search}
platform='ios'
/>
<View style={styles.discover}>
<FlatList data={this.state.articles} renderItem={this.renderItem} />
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
discover: {
flex: 1,
backgroundColor: "#FBFCFC",
alignItems: "center",
justifyContent: "center",
},
card: {
padding: 15,
},
});

getting lat/long coordinates from firebase/firestore collection

im relative new to react native and firebase and it would be awesome if anyone could help me with this problem. currently when im adding new posts to my firebase collection i display all post with a flatlist and it works fine. but is it possible to get only the currentLatitude and currentLongitude for my markers? my target is to generate a new marker for each post.
Events = []
this.firestore.collection("Events").get().then(snapshot => {
snapshot.forEach(doc => {
Events.push(doc.data())
})
})
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<MapView
provider={PROVIDER_GOOGLE}
mapType='hybrid'
showsUserLocation style={{flex: 1}}>
<MapView.Marker
coordinate={{latitude: //currentLatitude,
longitude: //currntLongitude}}
title={("Test")}
description={("Test")}
/>
</MapView>
</View>
</SafeAreaView>
);
}
}
#DevAS thanks for your patience.. this was made from 3 different .js files.. but I don't now how to get it just into the map.js.
The final result should look something like this:
enter image description here
Everything except for the lat/lng cords are supposed to be in the callout-window.
Item.js:
import { Ionicons } from '#expo/vector-icons';
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import Fire from '../screens/Fire'
const profileImageSize = 36;
const padding = 12;
export default class Item extends React.Component {
state = {
user: {}
};
componentDidMount() {
const user = this.props.uid || Fire.shared.uid;
this.unsubscribe = Fire.shared.firestore
.collection("users")
.doc(user)
.onSnapshot(doc => {
this.setState({ user: doc.data() });
});
if (!this.props.imageWidth) {
// Get the size of the web image
Image.getSize(this.props.image, (width, height) => {
this.setState({ width, height });
});
}
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { title, address, name, imageWidth, imageHeight, image, currentLatitude, currentLongitude } = this.props;
// Reduce the name to something
const imgW = imageWidth || this.state.width;
const imgH = imageHeight || this.state.height;
const aspect = imgW / imgH || 1;
return (
<View>
<Header image={{ uri: this.state.user.avatar }} name={this.state.user.name} />
<Image
resizeMode="contain"
style={{
backgroundColor: "#D8D8D8",
width: "100%",
aspectRatio: aspect
}}
source={{ uri: image }}
/>
<Metadata
name={this.state.user.name}
address={address}
title={title}
currentLongitude={currentLongitude}
currentLatitude={currentLatitude}
/>
</View>
);
}
}
const Metadata = ({ name, address, title, currentLongitude, currentLatitude}) => (
<View style={styles.padding}>
<IconBar />
<Text style={styles.text}>{name}</Text>
<Text style={styles.subtitle}>{address}</Text>
<Text style={styles.subtitle}>{title}</Text>
<Text style={styles.subtitle}>Lat: {currentLatitude}</Text>
<Text style={styles.subtitle}>Lng: {currentLongitude}</Text>
</View>
);
const Header = ({ name, image }) => (
<View style={[styles.row, styles.padding]}>
<View style={styles.row}>
<Image style={styles.avatar} source={image} />
<Text style={styles.text}>{name}</Text>
</View>
<Icon name="ios-more" />
</View>
);
const Icon = ({ name }) => (
<Ionicons style={{ marginRight: 8 }} name={name} size={26} color="black" />
);
const IconBar = () => (
<View style={styles.row}>
<View style={styles.row}>
<Icon name="ios-heart-empty" />
<Icon name="ios-chatbubbles" />
<Icon name="ios-send"/>
</View>
<Icon name="ios-bookmark" />
</View>
);
const styles = StyleSheet.create({
text: { fontWeight: "600" },
subtitle: {
opacity: 0.8
},
row: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
padding: {
padding
},
avatar: {
aspectRatio: 1,
backgroundColor: "#D8D8D8",
borderWidth: StyleSheet.hairlineWidth,
borderColor: "#979797",
borderRadius: profileImageSize / 2,
width: profileImageSize,
height: profileImageSize,
resizeMode: "cover",
marginRight: padding
}
});
List.js
import React from 'react';
import { FlatList } from 'react-native';
import Footer from './Footer';
import Item from './Item';
class List extends React.Component {
renderItem = ({ item }) => <Item {...item} />;
keyExtractor = item => item.key;
render() {
const { onPressFooter, ...props } = this.props;
return (
<FlatList
keyExtractor={this.keyExtractor}
ListFooterComponent={footerProps => (
<Footer {...footerProps} onPress={onPressFooter} />
)}
renderItem={this.renderItem}
{...props}
/>
);
}
}
export default List;
FeedScreen.js
import firebase from "firebase";
import React, { Component } from "react";
import { LayoutAnimation, RefreshControl } from "react-native";
import List from "../components/List";
import Fire from "./Fire";
// Set the default number of images to load for each pagination.
const PAGE_SIZE = 5;
console.disableYellowBox = true;
export default class FeedScreen extends Component {
state = {
loading: false,
data: {}
};
componentDidMount() {
// Check if we are signed in...
if (Fire.shared.uid) {
// If we are, then we can get the first 5 posts
this.makeRemoteRequest();
} else {
// If we aren't then we should just start observing changes. This will be called when the user signs in
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.makeRemoteRequest();
}
});
}
}
// Append the item to our states `data` prop
addPosts = posts => {
this.setState(previousState => {
let data = {
...previousState.data,
...posts
};
return {
data,
// Sort the data by timestamp
posts: Object.values(data).sort((a, b) => a.timestamp < b.timestamp)
};
});
};
// Call our database and ask for a subset of the user posts
makeRemoteRequest = async lastKey => {
// If we are currently getting posts, then bail out..
if (this.state.loading) {
return;
}
this.setState({ loading: true });
// The data prop will be an array of posts, the cursor will be used for pagination.
const { data, cursor } = await Fire.shared.getPaged({
size: PAGE_SIZE,
start: lastKey
});
this.lastKnownKey = cursor;
// Iteratively add posts
let posts = {};
for (let child of data) {
posts[child.key] = child;
}
this.addPosts(posts);
// Finish loading, this will stop the refreshing animation.
this.setState({ loading: false });
};
// Because we want to get the most recent items, don't pass the cursor back.
// This will make the data base pull the most recent items.
_onRefresh = () => this.makeRemoteRequest();
// If we press the "Load More..." footer then get the next page of posts
onPressFooter = () => this.makeRemoteRequest(this.lastKnownKey);
render() {
// Let's make everything purrty by calling this method which animates layout changes.
LayoutAnimation.easeInEaseOut();
return (
<List
refreshControl={
<RefreshControl
refreshing={this.state.loading}
onRefresh={this._onRefresh}
/>
}
onPressFooter={this.onPressFooter}
data={this.state.posts}
/>
);
}
}

Rendering Firebase data into FlatList

I am using React Native, Rematch for Redux and Firebase Firestore. I am attempting to pull data from my Firebase database and populate it inside my FlatList. The problem is, it is not giving me any error and it giving me a blank white screen. I do not know where I am going wrong.
This is what my database looks like - list of activities
This is what my Rematch for Redux store looks like:
import firebase from 'firebase';
import db from '../config/firebase'
const activity = {
state: {},
reducers: {
activities(state, payload) {
return {
...state,
...payload
}
},
},
effects: {
async getActivities() {
try {
const response = await db.collection('activities').get()
//console.log(response.docs.map(doc => doc.data()))
return dispatch({ type: 'activity/activities', payload: response.docs.map(doc => doc.data()) })
} catch (err) {
alert(err)
}
},
}
}
export default activity
Here is the component where I am using the FlatList:
import * as React from 'react';
import {
Text,
TouchableOpacity,
View,
FlatList,
ImageBackground
}
from 'react-native';
import styles from '../styles'
import { connect } from 'react-redux';
import '#expo/vector-icons';
import 'redux';
class Activities extends React.Component {
state = {
movetoArray: [],
outputActivity: [],
};
async componentDidMount() {
const activities = await this.props.getActivities()
this.state.movetoArray = Object.values(activities)
this.state.outputActivity = Object.entries(this.state.movetoArray[1]).map(item => ({ ...item[1], key: item[0] }));
//this.state.arrayActivity = Object.entries(activities).map(item => ({...item[1], key: item[0]}));
console.log(this.state.outputActivity)
}
_renderItem = ({ item }) => (
<TouchableOpacity
onPress={() => this.props.navigation.navigate('activitiesMD',
{
title: item.name,
objectData: item.data
})}>
<ImageBackground source={item.image} style={styles.inputTiles} imageStyle={{ borderRadius: 10 }}>
<View style={styles.inputTileTextView}>
<Text style={[styles.inputTileText, { color: item.colour }]}>{item.name}</Text>
</View>
</ImageBackground>
</TouchableOpacity>
);
render() {
const { routeName } = this.props.navigation.state
return (
<View style={styles.container}>
<FlatList
data={this.state.outputActivity}
keyExtractor={item => item.id}
renderItem={this._renderItem}
/>
</View>
);
}
}
const mapState = (state) => ({
activity: state.activity,
})
const mapDispatch = (dispatch) => ({
getActivities: () => dispatch.activity.getActivities(),
})
export default connect(mapState, mapDispatch)(Activities)
I do not know why I am getting this outcome. Please help me :)
If you directly mutate state in React then the component won't re-render. Please use this.setState({ ... }) like so:
- this.state.movetoArray = Object.values(activities)
- this.state.outputActivity = Object.entries(this.state.movetoArray[1]).map(item => ({ ...item[1], key: item[0] }));
+ this.setState({ movetoArray: Object.values(activities), outputActivity: Object.entries(this.state.movetoArray[1]).map(item => ({ ...item[1], key: item[0] })) })

React native component function promise return url onNavigationStateChange

I have a component, this component is nothing but a WebView.
I make a call to this component and I want a result back, through promises.
I have to make sure that after the WebView is loaded and running onNavigationStateChange, I have to return a Promise to return the result.
Main:
import * as React from 'react';
import { View } from 'react-native';
import ShortUrl from './ShortUrl';
export default class App extends React.Component {
componentDidMount() {
this.shortUrl
.init('https://www.cineblog.life/?trdownload=0&trid=24045&movie=0')
.then(uid => {
console.log('URL: ' + uid);
})
.catch(err => alert('error: ' + err));
}
render() {
return (
<View>
<ShortUrl
ref={r => (this.shortUrl = r)}
style={{ width: 0, height: 0, backgroundColor: '#000' }}
/>
</View>
);
}
}
ShortUrl:
import * as React from 'react';
import { View, WebView } from 'react-native';
export default class ShortUrl extends React.Component {
constructor() {
super();
this.state = {
initialUrl: '',
init: false,
//promise:
};
}
init(initialUrl) {
this.setState({ initialUrl, init: true });
return new Promise(async (resolve, reject) => {
resolve('OK');
});
}
onNavigationStateChange = navState => {
const { initialUrl } = this.state;
if (initialUrl !== navState.url) {
return new Promise(async (resolve, reject) => {
resolve(navState.url);
});
}
};
render() {
const { initialUrl, init } = this.state;
if (!init) return null;
return (
<View>
<WebView
source={{
uri: initialUrl,
}}
onNavigationStateChange={this.onNavigationStateChange}
style={{ flex: 1 }}
/>
</View>
);
}
}
Link expo: Here
I can't fully understand your question, but it seems you're simply looking for a function passed as prop to your child component. Once your promise is completed just call that function you have in prop and pass it a parameter, in order to handle it in the parent component.
In your Main:
[...]
<ShortUrl
ref={r => (this.shortUrl = r)}
style={{ width: 0, height: 0, backgroundColor: '#000' }}
handleResult={ resultArrivingFromChild => { // do what you want with the result }}
/>
In ShortUrl:
onNavigationStateChange = navState => {
[...] // do what you have to do
this.props.handleResult(resultYouWantToSendBack);
};

View not updating state Redux, React, Firebase

I am using redux to store and fetch my data from Firebase. The data is stored successfully, however, the view MyActivities is not updated with the new data. Am I doing something wrong here ?
I need to rerender the whole application for the views to be updated with the new data stored in Firebase.
I didn't add all the code used in this example.
ActivitiesAction.js
import firebase from 'firebase';
import { Navigation } from 'react-native-navigation';
import {
ACTIVITIES_FETCH_SUCCESS,
ACTIVITIES_SEND_SUCCESS,
SUBACTIVITY_SEND_SUCCESS
} from './types';
export const activitiesFetch = () => {
return (dispatch) => {
firebase.database().ref('users_data/s80GnOQu22W4XLLYbuKUBC2BzkY2/').once('value')
.then((snapshot) => {
dispatch({
type: ACTIVITIES_FETCH_SUCCESS,
payload: snapshot.val()
});
});
};
};
export const activitiesSend = (activityDescription,
activityDate, category, notification, alarm) => {
const ref = firebase.database()
.ref('users_data/s80GnOQu22W4XLLYbuKUBC2BzkY2/activities/cheduled_activities');
const activity = ref.push();
const ref2 = firebase.database()
.ref('users_data/s80GnOQu22W4XLLYbuKUBC2BzkY2/activities/all_activities');
const activityList = ref2.push();
return (dispatch) => {
activity.set({
activityDescription,
activityDate,
category,
// time: this.state.time,
notification,
alarm
}).then(activityCreated => {
dispatch({ type: ACTIVITIES_SEND_SUCCESS, payload: activityCreated });
activityList.set({
activityDescription,
category
}).then(listActivity => {
dispatch({ type: SUBACTIVITY_SEND_SUCCESS, payload: listActivity });
});
});
};
};
ActivitiesReducer.js
import {
ACTIVITIES_FETCH_SUCCESS,
ACTIVITIES_SEND_SUCCESS,
SUBACTIVITY_SEND_SUCCESS
} from '../actions/types';
const INITIAL_STATE = { activitiesData: '', activityCreated: null, listActivity: null };
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case ACTIVITIES_FETCH_SUCCESS:
return { ...state, activitiesData: action.payload };
case ACTIVITIES_SEND_SUCCESS:
return { ...state, activityCreated: action.payload };
case SUBACTIVITY_SEND_SUCCESS:
return { ...state, listActivity: action.payload };
default:
return state;
}
};
MyActivities.js
import React, { Component } from 'react';
import { Container, Content, View } from 'native-base';
import { connect } from 'react-redux';
import _ from 'lodash';
import { activitiesFetch } from '../actions/ActivitiesAction';
import Activity from './Activity';
class MyActivities extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.activitiesFetch();
}
componentWillReceiveProps(nextProps) {
this.setState({ activitiesData: nextProps });
console.log('next props:', nextProps);
}
componentWillUpdate(nextProps, nextState) {
console.log('next props:', nextProps);
}
renderActivities() {
// this.setState({ data: this.props.activitiesArray });
console.log('acti():', this.props.activitiesData);
const activitiesArray = _.values(this.props.activitiesData);
console.log('acti[]:', activitiesArray);
const list = _.values(activitiesArray[0]) || [];
const act = list.map((activities) => (activities));
console.log('acti[]:', act);
const activities = _.values(act[1]);
return (
activities.map((singleActivity, i) => (
<Activity
key={i}
Title={singleActivity.activityDescription}
Author={activitiesArray[1].full_name}
Time={singleActivity.time}
PeopleStats={'0'}
/>
))
);
}
render() {
return (
<Container>
{/* <HeaderActivities /> */}
<Content style={styles.Content}>
{/* <ScrollView style={{ flex: 1 }}> */}
<View style={styles.styleView}>
{this.renderActivities()}
</View>
{/* </ScrollView> */}
</Content>
</Container>
);
}
}
const mapStateToProps = state => {
return {
// activitiesArray: _.values(state.activitiesData)
activitiesData: state.activitiesData
};
};
const styles = {
Content: {
backgroundColor: '#F0F5F7',
},
styleView: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
alignItems: 'center',
// alignItems: 'flex-start',
// alignContent: 'flex-start'
},
ButtonActive: {
borderBottomColor: '#FF8600',
borderBottomWidth: 3,
paddingBottom: 3,
borderRadius: 0
}
};
export default connect(mapStateToProps, { activitiesFetch })(MyActivities);
Use the redux and react dev tools to check
did the expected action dispatch?
does the state change match your expectations?
do components have the props you expect them to have?

Resources