Realm crashes on create object (React Native) - android

This is my RealmService file:
import Realm from 'realm';
const AuthSchema = {
name: 'Auth',
primaryKey: 'id',
properties: {
id: {
type: 'int',
indexed: true
},
time: 'date',
username: 'string',
action: 'string'
}
}
const WiretransferSchema = {
name: 'Wiretransfer',
primaryKey: 'id',
properties: {
id: {
type: 'int',
indexed: true
},
time: 'date',
source: 'string',
target: 'string',
amount: 'float',
comments: {
type: 'string',
optional: true
}
}
}
let RealmService = {
findAllAuth: function() {
return repository.objects('Auth');
},
SaveAuth: function(username, action) {
Realm.open({
path: 'testtt.realm',
schema: [AuthSchema, WiretransferSchema]
}).then(realm => {
// Get max ID
var maxId = realm.objects('Auth').max('id');
realm.write(() => {
realm.create('Auth', {
id: maxId + 1,
time: Date.now(),
username: username,
action: action
}, true);
});
realm.close();
}).catch(err => {
console.log(err);
});
}
}
module.exports = RealmService;
The app crashes without any errors when this code is called:
realm.write(() => {
realm.create('Auth', {
id: maxId + 1,
time: Date.now(),
username: username,
action: action
}, true);
});
Just the write method doesn't crash the app. It's the create method.
If I disable the debugging tools in React Native the app doesn't crash but there is nothing in the realm file added.
I've tried RN 0.57.1 and 0.57.8. Reinstalled realm and still no luck. What could the problem be?

Make sure datatypes and objects you are passing are same. I got same crash when my datatype was int and I gave it string.
In your case passing new Date() will work.
It won't give any errors but app will crash on both android and iOS. Maybe realm team will solve it in future release as this bug already exists in Github forum.

Related

How to convert JSONObject to a JSONArray?

Recently,I got the problem when I tried to implement a comment function in an Android APP.
The definition of comments in user.js is as follow
comnents: [{
ownerID: {
type: String,
required: true,
},
commenterID: {
type: String,
required: true,
},
commenterName: String,
content: {
type: String,
require: true,
}
}],
And I have a request like that:
{
"_id":"60d204d6efc6c70022b08dc4",
"comments":[
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d205afefc6c70022b08dc8",
"commenterName":"Bob",
"content":"Hello World!"
},
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d20892efc6c70022b08dd2",
"commenterName":"Alice",
"content":"Hello Earth!"
}
]
}
Here is my API
router.post("/writecomment",jsonParser,
async(req,res,next)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({erros:errors.array()});
}
        User.findOneAndUpdate(
            { "_id": req.body._id},
            {
                $set: {
                    comments:req.body.comments
                }
            },
            {overwrite:true},
function(err,resp){
if(err) throw err;
if(resp) {
return res.send({
msg:' change successfully'
});
}else{
return res.status(403).json({ success: false, message: 'Failed to change'});
}
}
      )
}
)
How do I convert "comments" from request to comments array? Or have a better way to implement this function?
PS: I use Mongoose + Express Framework to develope.
const commentArray = [...req.body.comments]
Will make this for you:
[
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d205afefc6c70022b08dc8",
"commenterName": "Bob",
"content": "Hello World!"
},
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d20892efc6c70022b08dd2",
"commenterName": "Alice",
"content": "Hello Earth!"
}
]
Basically what is happening here is, we are iterating over the response you are getting and saving the result in an array. If you want to learn more about the ... operator, check out this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

MissingSchemaError: Schema hasn't been registered for model products

MissingSchemaError: Schema hasn't been registered for model products
getCartItems MissingSchemaError: Schema hasn't been registered for model "products".
Use mongoose.model(name, schema)
at NativeConnection.Connection.model (F:\ecommerceApp\ecommerce-backend\node_modules\mongoose\lib\connection.js:1242:11)
This is the controller
Cart
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
cartItems: [
{
product : {
type :mongoose.Schema.Types.ObjectId,
ref : "product",
required:true
},
quantity : {
type:Number,
default:1
}
}
]
} ,{timestamps:true});
module.exports = mongoose.model('Cart' , cartSchema , 'cart');
Products
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
slug: {
type: String,
required: true,
unique: true
},
quantity: {
type: Number,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true,
trim: true
},
offer: { type: Number },
productPictures: [{
img: { type: String }
}],
reviews: [{
userid: { type: mongoose.Schema.Types.ObjectId, ref: "User", review: String }
}],
category: { type: mongoose.Schema.Types.ObjectId, ref: "Categories" },
createdby: {
type: mongoose.Schema.Types.ObjectId, ref: "User", required: true
},
updatedAT: {
type: Date
}
}, { timestamps: true });
module.exports = mongoose.model('Product', productSchema);
Document
Products
{"_id":{"$oid":"6027d3a8cf712436607e6a6f"},"name":"Samsung Galaxy S21 Plus (Phantom Silver, 256 GB) (8 GB RAM)","slug":"Samsung-Galaxy-S21-Plus-(Phantom-Silver-256-GB)-(8-GB-RAM)","price":5000,"quantity":10,"description":"With the Samsung Galaxy S21 Plus Smartphone, you can click amazing shots and record stunning videos at up to 8K resolution as it comes with a 64 MP camera setup. This smartphone is 5G-ready, enabling you to stream videos and download content from the Web with minimal lag. Moreover, its powerful processor and long-lasting battery make it a delight to use this smartphone.","productPictures":[{"_id":{"$oid":"6027d3a8cf712436607e6a70"},"img":"wGFfBkAhQ-samsung-galaxy-j6-sm-j600gzbgins-original-imaf6zpf6q8tjcva.jpeg"}],"category":{"$oid":"6020d53117616c5228246ac4"},"createdby":{"$oid":"601400873e5a422f9c81ae1c"},"reviews":[],"createdAt":{"$date":"2021-02-13T13:27:04.135Z"},"updatedAt":{"$date":"2021-02-13T13:27:04.135Z"},"__v":0}
Cart
{"_id":{"$oid":"6027d3bacf712436607e6a71"},"user":{"$oid":"60238bea8f89fb538c845f5b"},"cartItems":[{"quantity":2,"_id":{"$oid":"6027d3d4cf712436607e6a73"},"product":{"$oid":"6027d3a8cf712436607e6a6f"}}],"createdAt":{"$date":"2021-02-13T13:27:22.393Z"},"updatedAt":{"$date":"2021-02-13T13:27:48.217Z"},"__v":0}
Router export method , Here is the error which is not populating the population not happening
Throws in when called from PostMan
exports.getCartItems = (req, res) => {
//const { user } = req.body.payload;
//if(user){
console.log('req.user._id' , req.user._id);
Cart.findOne({ user: req.user._id })
.populate("cartItems.product", "_id name price productPictures")
.exec((error, cart) => {
console.log('getCartItems' , error);
if (error) return res.status(400).json({ error });
if (cart) {
let cartItems = {};
cart.cartItems.forEach((item, index) => {
cartItems[item.product._id.toString()] = {
_id: item.product._id.toString(),
name: item.product.name,
img: item.product.productPictures[0].img,
price: item.product.price,
qty: item.quantity,
};
});
res.status(200).json({ cartItems });
}
});
//}
};
You have a typo. You mean products but typed proucts

iOS and Android native apps sharing React Native database

I maintain an app that has iOS and Android native versions, and now I and my pairs are considering migrate both to React Native. We want to do this step by step, so in the first moment, we consider that a good approach would be implementing the data layer into React Native and make the native apps consume the data through this hybrid layer. Is this possible? Sorry if this is a silly question, I never had any experience with React Native.
EDIT: The database would be primarily realm-js because we already have experience with Realm on Android - iOS uses Coredata and this is a reason for choosing this approach as well, have 2 database technology on the mobile side gave us some headaches already.
Here's an example on how to setup realm
import Realm from "realm";
// define your realm schemas
const TodoSchema: Realm.ObjectSchema = {
name: "todo",
primaryKey: "id",
properties: {
id: "int",
title: { type: "string", default: "untitled" },
body: { type: "string", default: "" },
isDone: { type: "bool", default: false},
},
};
interface ITodo {
title: string;
body: string;
isDone?: boolean;
}
class RealmDao {
private realmDao: Realm;
private static instance: RealmDao | null = null;
private constructor() {
this.realmDao = new Realm({
schema: [TodoSchema], // array of schemas
schemaVersion: 0,
});
}
// insuring that only one instance exists
public static getInstance = () => {
if (RealmDao.instance === null) {
RealmDao.instance = new RealmDao();
}
return RealmDao.instance;
};
public insert = (tableName: string, todo: ITodo) =>
this.realmDao.write(() => {
this.realmDao.create("todo", tableName);
});
};
public retrieveAll = (tableName: string) => {
return this.realmDao.objects(tableName);
};
}
const insert = (tableName: string, todo: ITodo) => {
RealmDao.getInstance().insert(tableName, todo);
}
const retrieveAll = (tableName: string) => {
RealmDao.getInstance().retrieveAll(tableName);
}
export { insert, retrieveAll };
Made it singleton to ensure that only one instance exists, I ran into a problem before where multiple instances of realm are running.
Now you can use the data in your component
import React from "react";
import { View, Text } from "react-native";
import { insert, retrieveAll } from "./realmDao";
const Example = () => {
React.useEffect(() => { insert({'title', 'something to be done'}); }, []);
return (
<View>
<Text>{JSON.stringify(retrieveAll ('todo'))}</Text>
</View>
)
);

Razor pay not working in react-native version 0.61.5. Android app crash on razorpayCheckout.open. Any solutions?

All parameters are holding proper values, but app crashes without logs RazorpayCheckout.open line.
let options = {
description: title,
image: 'https://cdn.razorpay.com/logos/DjijAUZBHCGlv4_medium.png',
currency: currency,
key: orderInfo.key,
amount: base_price,
name: 'dfgdfg',
order_id:orderInfo.order_id,
prefill: {
email: user.email,
contact: user.country_code + user.mobile_number,
name: user.first_name + ' ' + user.last_name
},
theme: { color: '#F37254' }
}
RazorpayCheckout.open(options).then((err,data) => {
console.log(err,data)
}).catch((error) => {
console.log(error)
});

React-native-payments: issue Unhandled Promise Rejection

It's about the react-native-payments from Naoufal
I follow the simple tutorial, all is good, installation, setting, and so on.
When I called paymentRequest.show(). I have the warning
Possible Unhandled Promise Rejection(id:0)
I've already write a message to the developer, maybe the issue is in its side, I don't know.
Here is the simple code:
const METHOD_DATA = [{
supportedMethods: ['android-pay'],
data: {
supportedNetworks: ['visa', 'mastercard', 'amex'],
currencyCode: 'USD',
environment: 'TEST', // defaults to production
paymentMethodTokenizationParameters: {
tokenizationType: 'NETWORK_TOKEN',
parameters: {
publicKey: 'your-public-key'
}
}
}
}];
const DETAILS = {
id: 'basic-example',
displayItems: [
{
label: 'Movie Ticket',
amount: { currency: 'USD', value: '15.00' }
}
],
total: {
label: 'Merchant Name',
amount: { currency: 'USD', value: '15.00' }
}
};
const paymentRequest = new PaymentRequest(METHOD_DATA, DETAILS);
paymentRequest.show().then((response) => {
console.log(response)
});
I just want to display the payment view.
Here is the link of tutorial:
https://github.com/naoufal/react-native-payments

Categories

Resources