Cannot read property 'transaction' of undefined . React Native - reactjs

I am new to React-Native and I was following the steps on the react-native-sqlite-storage on GitHub but I am unfortunately stuck on the transaction and I've tried enablePromises but it still doesn't work. I am kind of at loss on how to proceed.
import React from 'react';
import SQLite from 'react-native-sqlite-storage';
import { StyleSheet, Text, View, ListItem } from 'react-native';
export default function App() {
let db = SQLite.openDatabase(
{
name: 'users',
createFromLocation: 1,
},
successToOpenDB(),
failToOpenDB()
);
function successToOpenDB() {
db.transaction((tx) => {
tx.executeSql('SELECT * FROM USERS', [], (tx, results) => {
let dataLength = results.row.length;
alert(dataLength);
});
});
}
function failToOpenDB(err) {
console.log(err);
}
return (
<>
<View style={styles.header}>
<Text style={styles.headerText}>Title</Text>
</View>
</>
);
};
Thanks!

You are passing the success callback successToOpenDB function while making a connection to db and using "db" which is undedined and u are getting error "cannot read property transaction of undefined.So do not pass successToOpenDB funtion as a success callback.
errorCB(err) {
console.log("SQL Error: " + err);
},
successCB() {
console.log("SQL executed fine");
},
openCB() {
console.log("Database OPENED");
},
var db = SQLite.openDatabase({
name: 'users',
createFromLocation: 1,
}, openCB, errorCB);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Employees a, Departments b WHERE a.department = b.department_id', [], (tx, results) => {
console.log("Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`Employee name: ${row.name}, Dept Name: ${row.deptName}`);
}
// Alternatively, you can use the non-standard raw method.
/*
let rows = results.rows.raw(); // shallow copy of rows Array
rows.map(row => console.log(`Employee name: ${row.name}, Dept Name: ${row.deptName}`));
*/
});
});

Related

wildcard in prisma full text search with postgresql

So I want to implement search feature to my web. In mysql we have * wildcard for 0 or more character match. But it seems we don't have any for postgress sql, I already checked the prisma documentation but I found nothing. I also tried &> and &< but it doesnt work.
Here's my code.
import { PrismaClient } from "#prisma/client"
export default async function handler(req, res) {
const prisma = new PrismaClient()
var searchWords = req.query.search.split(" ")
searchWords = searchWords.map(word => {
// return `wildcard${word}wildcard`
return `${word}`
})
const query = searchWords.join(" | ")
console.log(query)
const data = await prisma.diary.findMany(
{
where: {
body: {
search: query
}, title: {
search: query
}
},
orderBy: {
timecreated: 'desc'
},
take: 10
}
)
data.map(x => {
x.timecreated = x.timecreated.toString()
x.lastedited = x.lastedited.toString()
return x
})
await prisma.$disconnect()
res.status(200).json(data)
}

Unable to use SQLite in React Native

I'm trying to use SQLite in my react-native project.
This is my sample code. I can open my database, but can't bring data from db.
Some people said SQLite does not work for SDK version 30. Maybe this is the problem
result
My code:
SQLite.DEBUG(true);
SQLite.enablePromise(true);
let db;
openDB = ()=>{SQLite.openDatabase(
{
name: 'recipe.db',
createFromLocation: 1,
},
(DB) => {
console.log('success opening recipe.db')
db = DB;
db.transaction((tx) => {
tx.executeSql(`SELECT * FROM recipe;`, [], (tx, results) => {
const rows = results.rows;
for (let i=0; i<rows.length; i++) {
console.log(rows.item(i));
}
})
})
},
error => {
console.error(error);
}
);
}

react-native SQLite-storage INSERT statement

I use react-native react-native-sqlite-storage in my project and I am struggling to insert data
I managed to successfully read the pre populated table I created in
./android/app/src/main/assets/Mydb.db
but the INSERT statement somehow does not work.
simplified sample code:
import React, { Component } from 'react';
import SQLite from 'react-native-sqlite-storage';
let db;
class App extends Component {
constructor(props) {
// SQLite connection / config settings
db = SQLite.openDatabase({ name: 'testTable', //Name of my table
createFromLocation: "~MyDB.db", // Name of my DB
});
}
selectExample = () => { // working
db.transaction((tx) => {
tx.executeSql('SELECT * FROM testTable', [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`My AWG: ${row.AWG}, My Metric: ${row.metric}`);
}
});
});
}
updateDatabase = () => { // not working
db.transaction((tx) => {
tx.executeSql('Insert into testTable (AWG, metric) VALUES (?,?)',
[28,0.5],
(tx,results) => {
console.log("Results", results.rowsAffected);
},(err) => {
console.error(err);
}
)
})
}
onPress = () => {
this.selectExample(); // working
this.updateDatabase(); // issue
}
render() {
return (
<View>
<TouchableOpacity style = {styles.button} onPress={() => this.onPress() } />
</View>
);
}
in the console I get Results 1 as feedback, so the query seems fine but when I open MyDB.db with the mac app: DB Browser for SQLite, no changes happened no new rows..
Am I missing something here?

Must contain a query definition

Iam new to react-native and appsync,graphql.we are trying to implement an appsync app using react-native when i tried to run its is throwing an error saying
14:16:38: Must contain a query definition.
* null:null in getQueryDefinition
- node_modules/apollo-cache-inmemory/lib/bundle.umd.js:649:64 in diffQueryAgainstStore
- node_modules/apollo-cache-inmemory/lib/bundle.umd.js:559:32 in readQueryFromStore
- node_modules/apollo-cache-inmemory/lib/bundle.umd.js:899:38 in read
- node_modules/apollo-cache-inmemory/lib/bundle.umd.js:992:23 in readQuery
* null:null in update
- node_modules/apollo-client/bundle.umd.js:1609:0 in
- node_modules/apollo-utilities/lib/bundle.umd.js:818:21 in tryFunctionOrLogError
* null:null in
- node_modules/apollo-cache-inmemory/lib/bundle.umd.js:961:22 in performTransaction
- node_modules/apollo-client/bundle.umd.js:1473:0 in markMutationResult
- node_modules/apollo-client/bundle.umd.js:797:20 in next
- node_modules/zen-observable-ts/node_modules/zen-observable/lib/Observable.js:150:3 in notifySubscription
- node_modules/zen-observable-ts/node_modules/zen-observable/lib/Observable.js:195:5 in onNotify
* null:null in next
- node_modules/zen-observable-ts/node_modules/zen-observable/lib/Observable.js:150:3 in notifySubscription
* null:null in flushSubscription
- node_modules/zen-observable-ts/node_modules/zen-observable/lib/Observable.js:190:26 in
* null:null in
- node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
- node_modules/promise/setimmediate/core.js:123:25 in
- ... 10 more stack frames from framework internals
I tried to trace out the error in apollo-cache but i couldnt find one.Am getting this when ever i press send button.
import React, { Component } from 'react';
import { KeyboardAvoidingView, Text, Button, TextInput, StyleSheet, Alert } from 'react-native';
export default class ChatInput extends Component {
constructor(props) {
super(props);
this.userid = props.userid;
this.state = {
text: ''
}
}
handleSend = () => {
if (this.state.text === '') {
return false;
}
const chat = {
userid: this.userid,
text: this.state.text,
createdAt: new Date().toISOString()
}
this.props.onSubmit(chat);
this.setState({
text: ''
})
this.textInput.clear();
}
render() {
return (
<KeyboardAvoidingView>
<TextInput ref={input => { this.textInput = input }} placeholder="Message.."
onChangeText={(text) => this.setState({text})} onSubmitEditing={this.handleSend}
autoFocus={true} blurOnSubmit={false} returnKeyType="send"></TextInput>
<Button title="Send" onPress={this.handleSend}></Button>
</KeyboardAvoidingView>
);
}
}
const ChatInputData = compose(
graphql(PostMessage, {
options: {
fetchPolicy: 'no-cache'
},props: (props) => ({
onSubmit: chat => {
props.mutate({
variables: chat,
optimisticResponse: {
__typename: 'Mutation',
post: {
__typename: ChatHistory,
id: chat.createdAt,
userid: chat.userid,
text: chat.text,
createdAt: chat.createdAt
}
},
update: (proxy, {data: {post}}) => {
const data = proxy.readQuery({ query: PostMessage });
data.listPostMessages.items.push(Object.assign({}, post));
proxy.writeData({query: listPostMessages, data});
}
})
}
})
})
)(ChatInput)
Please help me out!.Thanks in advance
At this line :
const data = proxy.readQuery({ query: PostMessage });
I do not see a reference to PostMessage where you want to define your query.
The error means that in the imported PostMessage, the query could not be found. Make sure it looks like this: (and not the shorthand equivalent)
query postMessage($id: ID!) {
postMessage(id: $id) {
id
title
}
}
I resolved this error by correcting my mutation ie PostMesssage in my case.This error
Must contain a query definition
mainly occur if your query is incorrect which you have written in graphql. Start seeing how you passing your variables and how you use them and how you define them.
I also got this error when I had added new resolver functions (in new files) but failed to include references to these resolvers into graphql's executable schema.

Meteor React publish merged collections

With Meteor (1.4.2.3) and React, I have the collection Objects which has an itemId which refers to the collection Items.
Currently I subscribe to the collection on the client side with:
export default createContainer(() => {
let objectsSub = Meteor.subscribe('allObjects');
var objects = Objects.find({}, {
transform: function (doc) {
doc.item = Items.findOne({
_id: doc.itemId
});
return doc;
}
}).fetch();
return {
objects: objects,
}
}, App);
This works perfect, but I think it is more elegant to merge the collections on the server side. However, none of the solutions I found seem to work
Transform at collection definition
const Objects = new Mongo.Collection('objects',
{
transform: function (doc) {
doc.item = Items.findOne({
_id: doc.itemId
})
}
});
The console gives:
Error: transform must return object
Transform at publish
if (Meteor.isServer) {
Meteor.publish('allObjects', function () {
return Objects.find({}, {
sort: { startedAt: -1 },
transform: function (doc) {
doc.item = Items.findOne({
_id: doc.itemId
});
return doc;
}
});
});
};
TypeError: Cannot read property 'name' of undefined
Where name is a property of Items
i usually do it in the publish like this:
Meteor.publish('allObjects', function () {
let cursor = Objects.find({}, {
sort: { startedAt: -1 });
});
let transformData = (fields) => {
fields.item = Items.findOne({
_id: fields.itemId
});
return fields;
};
let handle = cursor.observeChanges({
added: (id, fields) => {
fields = transformData(fields);
this.added('objects', id, fields);
},
changed: (id, fields) => {
fields = transformData(fields);
this.changed('objects', id, fields);
},
removed: (id) => {
this.removed('objects', id);
}
});
this.ready();
this.onStop(() => {
handle.stop();
});
}

Resources