Demo
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import '@babel/polyfill';
import React, {useEffect, useState} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {decode, encode} from 'base-64';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import SQLiteAdapterFactory from 'pouchdb-adapter-react-native-sqlite';
import SQLite from 'react-native-sqlite-2';
import {addRxPlugin, createRxDatabase} from 'rxdb';
let localdb = null;
let sub = null;
if (!global.btoa) {
global.btoa = encode;
}
if (!global.atob) {
global.atob = decode;
}
process.browser = true;
const SQLiteAdapter = SQLiteAdapterFactory(SQLite);
addRxPlugin(SQLiteAdapter);
addRxPlugin(require('pouchdb-adapter-http'));
const schema = {
title: 'Anonymous chat schema',
description: 'Database schema for an anonymous chat',
version: 0,
type: 'object',
properties: {
count: {
type: 'number',
default: 0,
},
},
};
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("App -> setCount", setCount)
createRxDatabase({
name: 'heroesdb',
adapter: 'react-native-sqlite', // the name of your adapter
multiInstance: false,
ignoreDuplicate: true,
})
.then((db) => {
localdb = db;
return localdb.collection({
name: 'count',
schema,
});
})
.then(() => {
return localdb.count.findOne().exec();
})
.then((result) => {
if (result === null) {
localdb.count.insert({});
}
sub = localdb.count.findOne().$.subscribe(function(raw) {
setTimeout(async () => {
const changeFunction = (oldData) => {
oldData.count = oldData.count + 1;
return oldData;
}
await raw.atomicUpdate(changeFunction);
}, 2000)
setCount(raw.count);
})
});
return () => {
sub.unsubscribe();
}
}, []);
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<Text>Count: {count}</Text>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;