Sending status updates through helper function in react native - javascript

I have the following screen where I call a helper function pouchDB_helper.sync() to gather a bunch of data for me.
The goal is to be able to record where in the function it is currently at so I can give a percent or a status update in my render()
I'm new to react / react-native so I'm not sure if this is the right way to go about doing it. I'd like to be able to keep it as a helper function if possible because I use this function in other areas, this is just the only place I actually need a status update on where it's at in the process.
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'flex-start',
justifyContent: 'center',
padding: "5%",
backgroundColor: "#fff",
width:"100%"
},
statusHeader: {
fontSize: 18,
fontWeight: "600",
marginBottom: 10,
textAlign:'center',
width:'100%'
}
});
type Props = {};
export default class SyncScreen extends Component<Props> {
static navigationOptions = {
title: 'Syncing Settings',
};
render() {
pouchDB_helper.sync().then((response) => {
//IT'S DONE
}, (error) => { alert("THERE WAS AN ERROR"); });
return (
<View style={styles.container}>
<Text style={styles.statusHeader}>Syncing, please wait..</Text>
<Text>WHERE I WANT TO CHANGE TEXT</Text>
</View>
);
}
}
pouchDB_helper example
note: This is just an example. I know the .get() won't take long enough to warrant a status but I'm just trying to understand the concept.
import React from 'react';
import { AsyncStorage } from 'react-native';
import PouchDB from 'pouchdb-react-native'
export async function sync() {
const company_id = await AsyncStorage.getItem('company_id');
const device_db = new PouchDB(company_id, {auto_compaction: true});
//STATUS UPDATE 1
return device_db.get("settings").then((s) => {
//STATUS UPDATE 2
return device_db.get("get_this").then((s) => {
//STATUS UPDATE 3
return device_db.get("get_that").then((s) => {
//STATUS UPDATE 4
}, (error) => { return false; });
}, (error) => { return false; });
}, (error) => { return false; });
}

Simple approach would be passing a function to the sync function which can change the state and set the desired text on component.
Example
constructor(props) {
super(props);
this.state = {
level: 'some init value'
};
}
onChangeState = (level) => {
this.setState({level});
}
componentDidMount() {
pouchDB_helper.sync(this.onChangeState).then((response) => {
//IT'S DONE
this.onChangeState('Finished');
}, (error) => { alert("THERE WAS AN ERROR"); });
}
render() {
return (
<View style={styles.container}>
<Text style={styles.statusHeader}>Syncing, please wait..</Text>
<Text>{`Current level is ${this.state.level}`}</Text>
</View>
);
}
export async function sync(changeState) {
const company_id = await AsyncStorage.getItem('company_id');
const device_db = new PouchDB(company_id, {auto_compaction: true});
//STATUS UPDATE 1
changeState(1);
return device_db.get("settings").then((s) => {
//STATUS UPDATE 2
changeState(2);
return device_db.get("get_this").then((s) => {
//STATUS UPDATE 3
changeState(3);
return device_db.get("get_that").then((s) => {
//STATUS UPDATE 4
changeState(4);
}, (error) => { return false; });
}, (error) => { return false; });
}, (error) => { return false; });
}

Related

TypeError: undefined is not a function (near '...this.state.profile.map...')

I am getting error again and again . I don't know why I am getting this error.
The response I am getting is also an array, I tried with console.log . Below is the proof
Response From the axios Api:
{
"CCompany": "Testing Company",
"CFName": "Rehan",
"CLName": "ahmed",
"CMName": "",
"CTelHome": "1-232-2323232",
"UID": "700002"
}
Below is the code:
import React, { Component } from 'react';
import { View, Text, Dimensions, BackHandler, ToastAndroid } from 'react-native';
import axios from 'axios';
import Card from './Card';
import CardSection from './CardSection';
import ProfileDetails from './ProfileDetails';
import AsyncStorage from '#react-native-community/async-storage';
// Create a component
class ProfileActivity extends Component {
constructor() {
super();
this.state = {
profile: [],
setUID: '',
isloading: true,
};
}
state = {
canBeClosed: false
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = () => {
if (this.props.navigation.isFocused()) {
if (this.state.canBeClosed)
return this.state.canBeClosed = false;
else {
setTimeout(() => { this.state.canBeClosed = false }, 3000);
ToastAndroid.show("Press Again To Exit !", ToastAndroid.LONG);
return this.state.canBeClosed = true
}
}
};
async componentDidMount() {
try {
if (this.state.setUID == null && this.state.profile == null) {
console.log('profile remove');
const user = await AsyncStorage.getItem('responseJson');
const parsed = JSON.parse(user);
if (parsed !== null) {
this.setState({ setUID: parsed.UID });
}
axios.get('https:/new.didx.net/didxapi/UserInfo.php?UID=' + this.state.setUID)
.then(response => this.setState({ profile: response.data }));
}
else {
this.setState({ setUID: "" });
this.setState({ profile: "" });
console.log('not remove');
const user = await AsyncStorage.getItem('responseJson');
const parsed = JSON.parse(user);
if (parsed !== null) {
this.setState({ setUID: parsed.UID });
}
axios.get('https:/new.didx.net/didxapi/UserInfo.php?UID=' + this.state.setUID)
.then(response => this.setState({ profile: response.data }));
}
}
catch (error) {
alert('Server Error!')
}
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
renderProfile() {
if (this.state.profile) {
console.log(this.state.profile);
return this.state.profile.map(profile => (
<ProfileDetails key={profile.UID} profile={profile} />
));
}
}
render() {
return (
<View style={styles.container}>
{this.renderProfile()}
</View>
);
}
}
export default ProfileActivity;
const h = Dimensions.get('screen').height * 0.01;
const w = Dimensions.get('screen').width * 0.01;
const styles = {
container: {
flex: 1,
backgroundColor: '#fff'
},
ViewStyle: {
paddingTop: h * 5,
},
TextStyle: {
justifyContent: 'flex-start',
// alignSelf: 'center',
color: '#000',
fontWeight: 'bold',
fontSize: 20,
padding: 5,
fontFamily: 'Roboto',
maxWidth: w * 50,
}
}
I tried everything I could to solve this problem.
.map expects an array ... but your axios.get('https:/new.didx.net/didxapi/UserInfo.php?UID=' + this.state.setUID) call returns an object like { UID: "1", CFName: "1", CMName: "", CLName: "1", CCompany: "1", CTelHome: "2" }

I got navigation as undefined in react navigation 5?

I have a reusable component for Sign in with Apple Button
After user success, i navigate hem to Home screen
But i notes when i log navigation it's log undefined,
and when i log this.props i just got the two actions i made in redux!
So how can i access to navigation in this component and why it's not accessed by default!
Log
props => {"isLogin": [Function isLogin], "storeToken": [Function storeToken]}
navigation => undefined
Code
import appleAuth, {
AppleAuthCredentialState,
AppleAuthError,
AppleAuthRealUserStatus,
AppleAuthRequestOperation,
AppleAuthRequestScope,
AppleButton,
} from '#invertase/react-native-apple-authentication';
import React from 'react';
import {ActivityIndicator, StyleSheet, View} from 'react-native';
import {connect} from 'react-redux';
import API from '../../api/API';
import {isLoginFunc} from '../../redux/actions/isLoginAction';
import {saveToken} from '../../redux/actions/saveTokenAction';
class AppleAuth extends React.Component {
constructor(props) {
super(props);
this.authCredentialListener = null;
this.user = null;
this.state = {
credentialStateForUser: -1,
loading: false,
};
}
componentDidMount() {
const {navigation} = this.props;
console.log('did-navigation', navigation);
console.log('did- this.props', this.props);
/**
* subscribe to credential updates.This returns a function which can be used to remove the event listener
* when the component unmounts.
*/
this.authCredentialListener = appleAuth.onCredentialRevoked(async () => {
// console.warn('Credential Revoked');
this.fetchAndUpdateCredentialState().catch(error =>
this.setState({credentialStateForUser: `Error: ${error.code}`}),
);
});
this.fetchAndUpdateCredentialState()
.then(res => this.setState({credentialStateForUser: res}))
.catch(error =>
this.setState({credentialStateForUser: `Error: ${error.code}`}),
);
}
componentWillUnmount() {
/**
* cleans up event listener
*/
this.authCredentialListener();
}
signIn = async () => {
// start a login request
try {
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: AppleAuthRequestOperation.LOGIN,
requestedScopes: [
AppleAuthRequestScope.EMAIL,
AppleAuthRequestScope.FULL_NAME,
],
});
this.setState({loading: true});
const {
user: newUser,
email,
nonce,
fullName: {familyName, givenName},
identityToken,
realUserStatus /* etc */,
} = appleAuthRequestResponse;
let username = `${givenName} ${familyName}`;
this.user = newUser;
this.fetchAndUpdateCredentialState()
.then(res => {
this.setState({credentialStateForUser: res});
console.log('res:::', res);
})
.catch(error => {
console.log(`Error: ${error.code}`);
this.setState({credentialStateForUser: `Error: ${error.code}`});
});
if (identityToken) {
console.log('email', email);
console.log('username', username);
console.log('nonce', nonce);
this.sendData(email, username, nonce);
// e.g. sign in with Firebase Auth using `nonce` & `identityToken`
} else {
// no token - failed sign-in?
}
if (realUserStatus === AppleAuthRealUserStatus.LIKELY_REAL) {
console.log("I'm a real person!");
}
// console.warn(`Apple Authentication Completed, ${this.user}, ${email}`);
} catch (error) {
if (error.code === AppleAuthError.CANCELED) {
alert('User canceled Apple Sign in');
// console.warn('User canceled Apple Sign in.');
} else {
console.error(error);
}
}
};
fetchAndUpdateCredentialState = async () => {
if (this.user === null) {
this.setState({credentialStateForUser: 'N/A'});
} else {
const credentialState = await appleAuth.getCredentialStateForUser(
this.user,
);
if (credentialState === AppleAuthCredentialState.AUTHORIZED) {
this.setState({credentialStateForUser: 'AUTHORIZED'});
} else {
this.setState({credentialStateForUser: credentialState});
}
}
};
// Send data "name,image,email" to API
sendData = async (Email, Name, Id) => {
try {
let response = await API.post('/apple', {
email: Email,
name: Name,
id: Id,
});
let {
data: {
data: {
response: {token},
},
},
} = response;
console.log('token:?>:', token);
console.log('props', this.props);
console.log('navigation', this.props.navigation);
this.setState({loading: false});
this.props.storeToken(token);
this.props.isLogin(true);
// this.props.navigation.push('BottomTabNavigator');
} catch (err) {
console.log(err);
alert('Unexpected Error, try again later.');
this.setState({loading: false});
}
};
render() {
return (
<View style={styles.container}>
{this.state.loading ? (
<ActivityIndicator />
) : (
<AppleButton
style={styles.appleButton}
cornerRadius={5}
buttonStyle={AppleButton.Style.WHITE}
buttonType={AppleButton.Type.SIGN_IN}
onPress={() => this.signIn()}
/>
)}
</View>
);
}
}
const styles = StyleSheet.create({
appleButton: {
width: 200,
height: 50,
// margin: 10,
},
container: {
flex: 1,
justifyContent: 'center',
},
});
const mapDispatchToProps = dispatch => {
// to excute the actions we want to invok
return {
isLogin: isLogin => {
dispatch(isLoginFunc(isLogin));
},
storeToken: token => {
dispatch(saveToken(token));
},
};
};
export default connect(
null,
mapDispatchToProps,
)(AppleAuth);
-
singin.js
<AppleAuth /> in the render method
if you render your component as component, not as a navigation screen, it will not receive navigation prop. It was like this in all versions of react-navigation
Access the navigation prop from any component

Redux store isn't getting updated

I have built this app using create-react-native-app, the action is dispatched but the state isn't being updated and I'm not sure why.
I see the action being logged (using middleware logger) but the store isn't getting updated, I am working on Add_Deck only for now
Here is my reducer:
// import
import { ADD_CARD, ADD_DECK } from './actions'
// reducer
export default function decks(state ={}, action){
switch(action.type){
case ADD_DECK:
return {
...state,
[action.newDeck.id]: action.newDeck
}
case ADD_CARD:
return {
...state,
[action.deckID]: {
...state[action.deckID],
cards: state[action.deckID].cards.concat([action.newCard])
}
}
default: return state
}
}
Actions file:
// action types
const ADD_DECK = "ADD_DECK";
const ADD_CARD = "ADD_CARD";
// generate ID function
function generateID() {
return (
"_" +
Math.random()
.toString(36)
.substr(2, 9)
);
}
// action creators
function addDeck(newDeck) {
return {
type: ADD_DECK,
newDeck
};
}
// export
export function handleAddDeck(title) {
return dispatch => {
const deckID = generateID();
// const newDeck = { id: deckID, title, cards: [] };
dispatch(addDeck({ id: deckID, title, cards: [] }));
};
}
function addCard(deckID, newCard) {
// { question, answer }, deckID
return {
type: ADD_CARD,
deckID,
newCard
};
}
// export
export function handleAddCard(deckID, content) {
// { question, answer }, deckID
return dispatch => {
const newCard = { [generateID()]: content };
dispatch(addCard(deckID, newCard));
};
}
And react-native component:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import {red, white} from '../utils/colors'
import { connect } from 'react-redux'
import { handleAddDeck } from '../redux/actions'
class AddDeck extends Component {
state = {
text:""
}
handleSubmit = () => {
this.props.dispatch(handleAddDeck(this.state.text))
this.setState(()=>{
return { text: ""}
})
}
render() {
return (
<View style={styles.adddeck}>
<Text> This is add deck</Text>
<TextInput
label="Title"
style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Deck Title"
value={this.state.text}
/>
<TouchableOpacity style={styles.submitButton} onPress={this.handleSubmit}>
<Text style={styles.submitButtonText}>Create Deck</Text>
</TouchableOpacity>
</View>
);
}
}
function mapStateToProps(decks){
console.log("state . decks", decks)
return {
decks
}
}
export default connect(mapStateToProps)(AddDeck);
const styles = StyleSheet.create({
adddeck: {
marginTop: 50,
flex: 1
},
submitButton: {
backgroundColor: red,
padding: 10,
margin: 15,
height: 40,
},
submitButtonText: {
color: white
}
});
I guess you forgot to export your types from the actions file thus the switch(action.type) does not trigger the needed case statement.
Maybe try to add as the following:
export const ADD_DECK = "ADD_DECK";
export const ADD_CARD = "ADD_CARD";
Or further debugging just to see if the values are the ones what you are looking for:
export default function decks(state = {}, action) {
console.log({type:action.type, ADD_DECK}); // see what values the app has
// further code ...
}
I hope that helps! If not, let me know so we can troubleshoot further.

React-Native: Warning: Can't perform a React state update on an unmounted component

I am getting the following error message when I try to transition from one screen to another:
This is happening in a game app where multiple phones are involved in the game and have different screens depending on their role in the game and depending if that phone is hosting the game or is a guest.
The following image shows this error message when I am trying to reach the next screen (on the left phone). The screen on the left phone is supposed to be the same as the one on the right, but without the buttons "Next Round" and "End Game". But I am getting a totally different screen with the error message:
Here is the code for the previous screen that is supposed to navigate the phones to this "score" screen:
import React, {Component} from 'react';
import {AppRegistry, View, Text, ScrollView, StyleSheet} from 'react-native';
import {CardFlip1} from '../components/CardFlip1';
import {CardFlip2} from '../components/CardFlip2';
import colors from '../config/colors';
import {PrimaryButton} from '../components/PrimaryButton';
import AsyncStorage from '#react-native-community/async-storage';
import Orientation from 'react-native-orientation-locker';
window.navigator.userAgent = 'react-native';
import io from 'socket.io-client/dist/socket.io';
class judge_screen extends Component {
constructor (props) {
super(props);
this.state = {
game_round: '',
player1: '',
player2: '',
label1: '',
label2: '',
current_user: ''
}
}
componentWillMount = () => {
this.getActives();
}
componentDidMount() {
Orientation.lockToLandscape();
this.socket = io("socket address is here", {
jsonp: false
});
}
getActives = async () => {
let user = await AsyncStorage.getItem('email');
let player_1 = await AsyncStorage.getItem('Player1');
let player_2 = await AsyncStorage.getItem('Player2');
let round = await AsyncStorage.getItem('Round');
this.setState({game_round: round});
this.setState({player1: player_1});
this.setState({player2: player_2});
var label_start = "Choose ";
var label_end = "'s fate";
var player_1_name = this.state.player1;
var player_2_name = this.state.player2;
var label1_str = label_start.concat(player_1_name, label_end);
this.setState({label1: label1_str});
var label2_str = label_start.concat(player_2_name, label_end);
this.setState({label2: label2_str});
}
player1Win = async () => {
let host = await AsyncStorage.getItem('host');
if (host == 'yes') {
let user = await AsyncStorage.getItem('email');
this.setState({current_user: user});
} else {
let user = await AsyncStorage.getItem('users_id');
this.setState({current_user: user});
}
var user_fix = this.state.current_user;
let player_name = await AsyncStorage.getItem('Player1');
AsyncStorage.setItem('Winner', player_name);
fetch('fetch address is here', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
email: user_fix,
Name: player_name,
Host: host
})
}).then((response) => response.json())
.then((responseJson) => {
if (host == 'yes') {
this.socket.emit('end_round', 'end');
this.props.navigation.navigate('end_round_host_screen');
} else {
// This is the navigation to the screen getting the error:
this.socket.emit('end_round', 'end');
this.props.navigation.navigate('end_round_guest_screen');
}
}).catch((error) => {
console.error(error);
});
}
player2Win = async () => {
let host = await AsyncStorage.getItem('host');
if (host == 'yes') {
let user = await AsyncStorage.getItem('email');
this.setState({current_user: user});
} else {
let user = await AsyncStorage.getItem('users_id');
this.setState({current_user: user});
}
var user_fix = this.state.current_user;
let player_name = await AsyncStorage.getItem('Player2');
AsyncStorage.setItem('Winner', player_name);
fetch('fetch address is here', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
email: user_fix,
Name: player_name,
Host: host
})
}).then((response) => response.json())
.then((responseJson) => {
if (host == 'yes') {
this.socket.emit('end_round', 'end');
this.props.navigation.navigate('end_round_host_screen');
} else {
// This is the navigation to the screen getting the error:
this.socket.emit('end_round', 'end');
this.props.navigation.navigate('end_round_guest_screen');
}
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<ScrollView>
<View style={{flexDirection: 'row'}}>
<View style={styles.container}>
<Text style={[styles.text]}>
{this.state.player1}
</Text>
<CardFlip1 />
<PrimaryButton
onPress={() => this.player1Win()}
label={this.state.label1}
>
</PrimaryButton>
</View>
<View style={styles.container}>
<Text style={[styles.text]}>
{this.state.player2}
</Text>
<CardFlip2 />
<PrimaryButton
onPress={() => this.player2Win()}
label={this.state.label2}
>
</PrimaryButton>
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: colors.backgroundColor,
margin: 10,
paddingBottom: 5,
borderWidth: 1,
borderColor: colors.borderColor,
},
text: {
fontSize: 18,
color: colors.primaryText,
marginTop: 10,
},
textPadding: {
paddingBottom: 10,
},
headingText: {
fontSize: 24,
fontWeight: '500',
color: colors.primaryText,
margin: 10,
},
textMarginHorizontal: {
marginHorizontal: 10,
},
})
export default judge_screen;
Here is the code for the "end_round_guest_screen" that I am trying to navigate to:
import React, {Component} from 'react';
import {View, Text, ScrollView, StyleSheet} from 'react-native';
import colors from '../config/colors';
import {PrimaryButton} from '../components/PrimaryButton';
import {ScoreBoardGuest} from '../components/ScoreBoardGuest';
import AsyncStorage from '#react-native-community/async-storage';
import Orientation from 'react-native-orientation-locker';
window.navigator.userAgent = 'react-native';
import io from 'socket.io-client/dist/socket.io';
class end_round_guest_screen extends Component {
constructor (props) {
super(props);
this.state = {
game_round: '',
winner: ''
}
}
componentWillMount = () => {
this.getActives();
this.getWinner();
}
componentDidMount() {
Orientation.unlockAllOrientations();
this.socket = io("socket address is here", {
jsonp: false
});
this.socket.on('next_round', () => this.nextRound());
this.socket.on('end_game', () => this.endGame());
}
getActives = async () => {
let round = await AsyncStorage.getItem('Round');
this.setState({game_round: round});
}
getWinner = async () => {
let user = await AsyncStorage.getItem('users_id');
//let host = await AsyncStorage.getItem('host');
fetch('fetch address is here', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
email: user
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({winner: responseJson});
}).catch((error) => {
console.error(error);
});
}
nextRound = () => {
this.props.navigation.navigate('round_start_guest_screen');
}
endGame = () => {
this.props.navigation.navigate('end_game_guest_screen');
}
render() {
return (
<ScrollView>
<View style={{alignItems: 'center'}}>
<Text style={styles.headingText}>
Round {this.state.game_round}
</Text>
<Text style={styles.text}>
{this.state.winner} wins this round!
</Text>
</View>
<View style={styles.container}>
<ScoreBoardGuest />
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: colors.backgroundColor,
margin: 10,
paddingVertical: 5,
borderWidth: 1,
borderColor: colors.borderColor,
},
text: {
fontSize: 18,
color: colors.primaryText,
marginTop: 10,
},
headingText: {
fontSize: 24,
fontWeight: '500',
color: colors.primaryText,
margin: 10,
},
})
export default end_round_guest_screen;
The "end_round_guest_screen" shows for a second or 2 without any states loaded and then goes to that "Card Back" screen with the error message.
The stacktrace shows that the error is happening inside the end_round_guest_screen. Based on your description that it is displayed for 2 seconds before navigating to "Card Back" with an error, I assume that it's happening on the line this.setState({winner: responseJson}) inside the fetch callback.
This could happen if the fetch request is still waiting for the response, then either the nextRound or endGame handler got called, which triggered the navigation, and therefore the unmount. By the time fetch got the data, and is about to call setState, the component is no longer mounted.
There are two ways to solve this generally.
1.) (Anti-pattern) Track whether component is still mounted using the componentDidMount/componentWillUnmount callback, then perform the isMounted check before calling setState.
componentDidMount() {
this.isMounted = false
}
componentWillUnmount() {
this.isMounted = false
}
getWinner = async () => {
//inside fetch
if (this.isMounted) {
this.setState({winner: responseJson})
}
}
2.) (Recommended) Cancel any pending network requests in componentWillUnmount callback using.
For example, you can use an AbortController to cancel fetch request. See https://stackoverflow.com/a/53435967/803865 for sample code.

React Native connection with SQLite database

I'm new with React Native and i would like to know if I can connect with a local SQLite database file (.db) i followed some guide on Github but it doesn't work for me, is there any other way to do it?? (using Android)
Here is the guide I said: https://github.com/andpor/react-native-sqlite-storage
global.db = SQLite.openDatabase(
{
name: "silkyMarket",
location: "default",
createFromLocation: "~SQLite.db",
},
() => {},
(error) => {
console.log("ERROR: " + error);
}
);
function SettingsScreen() {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Settings!</Text>
</View>
);
}
add that to your app's entry file like app.js of index.js then you can access it in other files like this:
import React from "react";
import SQLite from "react-native-sqlite-storage";
export default class SQLiteScreen extends React.Component {
constructor() {
super();
SQLite.DEBUG = true;
}
ExecuteQuery = (sql, params = []) =>
new Promise((resolve, reject) => {
db.transaction((trans) => {
trans.executeSql(
sql,
params,
(trans, results) => {
resolve(results);
},
(error) => {
reject(error);
}
);
});
});
// Create Table
async CreateTable() {
let Table = await this.executeQuery(
"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY NOT NULL, first_name VARCHAR(16), last_name VARCHAR(16), is_deleted INTEGER)",
[]
);
console.log(Table);
}
}

Categories

Resources