i want to save data in nativescript using API, but error JS: [Error: Network error: Converting circular structure to JSON] - api

i want to save result in nativescript, but show error JS: [Error: Network error: Converting circular structure to JSON]
in list.vue i push the id from each button +/-. here is the code
confirm() {
// The result property is true if the dialog is closed with the OK button, false if closed with the Cancel button or undefined if closed with a neutral button.
this.duhmboh=[]
this.pageData.forEach((element,index) => {
if(element.qty>0){
this.duhmboh.push({
id:element.id,
guest: this.guests[index],
qty: element
})
}
});
this.duhmboh.forEach(element => {
console.log("DUMBOH",element)
});
this.$showModal(modal, {
props: {
tempData: this.duhmboh
},
fullscreen: false,
animated: false,
stretched: false,
dimAmount: 0.2,
dismissEnabled: false
})
},
and the modal.vue is like this
save(qty) {
if (this.is_saving) return
this.is_saving = true
var vm = this
this.$apollo.query({
query: gqlUseVoucher,
variables: {
id: this.pageData.id,
qty_used: qty
},
fetchPolicy: 'no-cache'
}).then((resp) => {
if (resp.room.AuthorizeVoucherUsingID) {
vm.is_saving = false
vm.$modal.close()
vm.$store.commit('setSuccess', 'Voucher breakfast berhasil divalidasi')
} else {
vm.is_saving = false
errorHandler(vm, null, 'Voucher breakfast tidak dapat digunakan')
}
}).catch((error) => {
vm.is_saving = false
console.log(error)
errorHandler(vm, error)
})
},
and i still cant click the button ssave. what should i do?

Related

Ant Design Vue | Upload in Form | How to set initialValue

I'm having problems defining the initialValue in an Upload component, other thing I tried was using a watcher and updating the formValue and the method that update the props FileList. ¿Someone has any idea how this work?
Parent.vue
<Child :file="file"/>
...
async loadFile(item) {
this.loading = true
const { data } = await axios(..., {
...
responseType: 'blob',
})
const file = new File([data], item.name, { type: data.type });
this.file= {
Id: item.id,
Type: item.attributes.type,
IsPublic: item.attributes.is_public,
Descr: item.attributes.descr,
File: [file]
}
this.showForm();
this.loading = false
},
Children.vue
<a-upload
:accept="formats"
:before-upload="beforeUploadEvt"
:disabled="!formats"
:remove="removeFileEvt"
v-decorator="[
'File',
{
valuePropName: 'fileList',
getValueFromEvent: getValueEvt,
rules: [{ required: true, message: 'Select a file' }]
},
]" >
<a-button> <a-icon type="upload" /> Select a file</a-button>
</a-upload>
methods: {
beforeUploadEvt(file) {
this.form.setFieldsValue({
File: [file]
});
return false;
},
removeFileEvt() {
this.formulario.setFieldsValue({
Archivo: []
});
},
getValueEvt(e) {
if (Array.isArray(e)) {
return e;
}
if(e && e.fileList.length > 1) {
return e && [e.fileList[1]];
}
return e && e.fileList;
},
},
watch: {
adjunto: {
immediate: true,
deep: true,
handler(obj) {
if(obj.File) {
this.getValueEvt(obj.File);
// this.formulario.setFieldsValue({
// File: obj.File
// });
}
}
}
}
Trying the most basic example I could think, using the property defaultFileList
<a-upload
:accept="formats"
:before-upload="beforeUploadEvt"
:disabled="!format"
:remove="removeFileEvt"
:default-file-list="this.file.File">
<a-button> <a-icon type="upload" /> Select file</a-button>
</a-upload>
And then, this is the console warnings and errors I got, so seems to be something about type.
If anyone still seeking for an answer for this. You don't need to load file, wrapping your data in appropriate object helps. As in this example
fileList: [{
uid: '-1',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
}]
<a-upload
....
:file-list="fileList"
>

Sequelize 'upsert' doesn't function as it should be

A little background
Well, I was trying to use upsert command, however I keep getting errors, and I had no idea what went wrong, I already input the object that I want upsert (that is NewIssue) which is a value based on other call.
What it does
Error :(
{
"name": "SequelizeDatabaseError",
"parent": {
"fatal": false,
"errno": 1064,
"sqlState": "42000",
"code": "ER_PARSE_ERROR",
"sql": "INSERT INTO `ms_issue` VALUES () ON DUPLICATE KEY UPDATE ;"
},
"original": {
"fatal": false,
"errno": 1064,
"sqlState": "42000",
"code": "ER_PARSE_ERROR",
"sql": "INSERT INTO `ms_issue` VALUES () ON DUPLICATE KEY UPDATE ;"
},
"sql": "INSERT INTO `ms_issue` VALUES () ON DUPLICATE KEY UPDATE ;"
}
My code
Data Schema:
const Issue = sequelize.define('ms_issue', {
id_Issue: {
type: Sequelize.NUMBER,
primaryKey: true
},
id_IssueTag: {
type: Sequelize.NUMBER,
},
datetime_Issued: {
type: Sequelize.NOW
},
subject_Issue: {
type: Sequelize.STRING
},
desc_Issue: {
type: Sequelize.STRING
},
status_Issue: {
type: Sequelize.STRING
}
}, { timestamps: false, freezeTableName: true });
app.put('/issues/:id', (req, res) => {
const id_Staff = req.body.id_Staff
if (typeof id_Staff !== 'undefined' && typeof id_Staff === 'number') {
const id_Issue = parseInt(req.params.id)
if (typeof id_Issue !== 'undefined' && typeof id_Issue === 'number') {
Issue.findByPk(id_Issue)
.then(issue => {
if (issue) {
const newIssue = {
subject_Issue: req.body.subject || undefined,
desc_Issue: req.body.description || undefined,
id_IssueTag: req.body.tag || undefined
}
for (const obj in newIssue) {
if (typeof newIssue[obj] !== 'undefined') {
issue[obj] = newIssue[obj]
}
}
const NewIssue = issue
return NewIssue
} else res.status(404).send("Issue not found")
})
.then(NewIssue => {
return Issue.upsert(NewIssue)
.then(bool => {
if (bool === true) {
res.status(200).send("Issue has been updated")
res.status(200).send(NewIssue)
}
})
.catch(err => {
res.status(500).send(err)
})
})
.catch(err => {
console.log(err)
res.status(500).send("Cannot connect to database")
})
} else {
res.status(400).send("Invalid parameters: require 'id_Issue'")
}
} else {
res.status(401).send("Unauthorized access")
}
})
What I wanted
Able to insert/update on request in MariaDB. And explanation :)
The generated SQL is invalid - there are no values:
"sql": "INSERT INTO `ms_issue` VALUES () ON DUPLICATE KEY UPDATE ;"
The SQL should be valid if you specify, roughly as below:
...
Issue.upsert({
id_Issue: id_Issue,
subject_Issue: NewIssue.subject_Issue,
id_IssueTag : NewIssue.id_IssueTag,
...

Is there a way to do pagination with firebase realtime database (vuejs)?

I'm trying to paginate my data from firebase realtime database.
Do I have to change to firestore ? Where all is explain in Google's doc (https://firebase.google.com/docs/firestore/query-data/query-cursors) or it's also possible with rtdb ?
Here is my code (i'm using vue js) :
loadConcerts ({commit}) {
commit('setLoading', true)
firebase.database().ref('concerts')
.orderByChild('expires')
.startAt(Date.now() / 1e3)
.limitToFirst(10)
.once('value')
.then(data => {
const concerts = []
data.forEach(element => {
concerts.push({
id: element.key,
title: element.val().title,
day: element.val().day,
ticketlink: element.val().ticketlink,
description: element.val().descriptio
})
})
commit('setLoadedConcerts', concerts)
commit('setLoading', false)
})
.catch(
(error) => {
console.log(error)
commit('setLoading', false)
}
)
},
I would like to add pagination after 10 results, or infinite scrolling.
I have also had similar problem with pagination. The documentation seems to be insufficient i.e they show you how to go to next page but not how to move back to the previous page. Its just frustrating really.
I am using firestore
Below is how i implemented a simple pagination. I have already configured VueFire , Firebase and BootstrapVue i'll head straight to the code.
What to do different that no one shows you.
Use VueFire programmatic binding instead of declarative binding see here
To get firstVisible item in firebase run documentSnapshots.docs[0]
<template>
<div>
<p>{{countries}}</p>
<b-button-group size="lg" class="mx-2">
<b-button :disabled="prev_btn" #click="previous" >«</b-button>
<b-button :disabled="next_btn" #click="next">»</b-button>
</b-button-group>
</div>
</template>
<script>
import firebase from 'firebase/app'
import 'firebase/auth'
import { db } from '../main'
export default {
name: 'Countries',
data () {
return {
countries: [],
limit: 2,
lastVisible: '',
firstVisible: '',
next_btn: false,
prev_btn: true
}
},
methods: {
next () {
if (!this.next_btn) {
// bind data with countries
this.$bind('countries', db.collection('Countries').orderBy('createdAt').startAfter(this.lastVisible).limit(this.limit))
// set last and first visible items
db.collection('Countries').orderBy('createdAt').startAfter(this.lastVisible).limit(this.limit).get().then(documentSnapshots => {
this.lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1]
this.firstVisible = documentSnapshots.docs[0]
}).then(() => {
// Peep on the next next query to see if it gives zero
db.collection('Countries').orderBy('createdAt').startAfter(this.lastVisible).limit(this.limit).get()
.then(snap => {
if (snap.size === 0) {
//disable button if the next peeped result gets zero
this.next_btn = true
// enable previous button
this.prev_btn = false
} else {
// enable next button if peeped result is not zero
this.next_btn = false
// enable previous button
this.prev_btn = false
}
})
})
}
},
previous () {
// Ensure previous is not zero
db.collection('Countries').orderBy('createdAt').endBefore(this.firstVisible).limitToLast(this.limit).get().then(snap => { return snap.size })
.then(size => {
//confirm is not zero here
if (size !== 0) {
//bind the previous to countries
this.$bind('countries', db.collection('Countries').orderBy('createdAt').endBefore(this.firstVisible).limitToLast(this.limit))
// Set last and first visible
db.collection('Countries').orderBy('createdAt').endBefore(this.firstVisible).limitToLast(this.limit).get().then(documentSnapshots => {
this.lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1]
this.firstVisible = documentSnapshots.docs[0]
}).then(() => {
// peep the next previous query
db.collection('Countries').orderBy('createdAt').endBefore(this.firstVisible).limitToLast(this.limit).get()
.then(snap => {
if (snap.size === 0) {
//if next peeped previous button gets 0 disable
this.prev_btn = true
this.next_btn = false
} else {
//if next peeped result is does not get 0 enable buttons
this.prev_btn = false
this.next_btn = false
}
})
})
}
})
}
},
mounted () {
// run first query and bind data
this.$bind('countries', db.collection('Countries').orderBy('createdAt').limit(this.limit))
// set last and first Visible
db.collection('Countries').orderBy('createdAt').limit(this.limit).get().then(documentSnapshots => {
this.lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1]
this.firstVisible = documentSnapshots.docs[0]
}).then(() => {
// peep to check if next should be on or off
db.collection('Countries').orderBy('createdAt').startAfter(this.lastVisible).limit(this.limit).get()
.then(snap => {
if (snap.size === 0) {
this.next_btn = true
}
})
})
}
}
</script>

jQuery DataTables save scroll position after dialog pop-up

I have a table that shows a pop-up when the first cell is clicked like this:
$('#tblAllUsers tbody').on('click', 'td', function () {
var visIdx = $(this).index();
if (visIdx != 0) {
return false;
}
var par = this.parentNode.parentNode.id;
var oTable = $("#tblAllUsers").dataTable();
var rowIndex = $(this).closest('tr').index();
var aPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(aPos[0]);
var name = aData[1];
if (name != '') {
GetUser(name, rowIndex, "#tblAllUsers");
}
else {
ErrorDialog("#MessageDialog", "#lblError", "The User ID is blank in that row.", "No User ID");
return false;
}
});
The pop-up allows the user to modify fields and save it, close the dialog and then return to the grid. If the dialog is canceled, data not saved, the scroll is maintained. But if the data is saved, and I am not reloading the table, the table moves to the top. The AJAX update function is within the pop-up:
$.ajax({
type: 'POST',
data: $("#formUserModification").serializeArray(),
url: '#Url.Action("UpdateUser")',
success: function (data) {
if (data.Errors === 'ERROR') {
ErrorDialog("#MessageDialog", "#lblError", "There was an error encountered in modifying the user, please try again later.", "Error");
}
else {
updateTable(data);
}
$("#divDetails").dialog('close');
},
beforeSend: function () {
$("#divOverlay").show();
},
complete: function () {
$("#divOverlay").hide();
}
});
The update function simply loads the row:
function updateTable(data) {
var tab = $("#tblAllUsers").dataTable();
tab.fnUpdate(data.LastName + ', ' + data.FirstName, data.RowIndex, 0);
tab.fnUpdate(data.ID, data.RowIndex, 2);
tab.fnUpdate(data.LocationText, data.RowIndex, 3);
tab.fnUpdate(data.SiteText, data.RowIndex, 4);
}
Is there a way with this setup to keep the scroll position?
I accomplished my goal by doing this:
Define a variable:
var scrollToPos;
In the dialog definition set the value when it is opened and place the scroll bar when it is closed:
$("#divAllUsersDetail").dialog({
autoOpen: false,
width: '90%',
resizable: false,
draggable: false,
title: 'Details',
position: { my: 'top', at: 'top+100' },
modal: true,
closeOnEscape: false,
open: function() {
scrollToPos = $("#divAllUsers").find(".dataTables_scrollBody").scrollTop();
},
close: function () {
$("#divAllUsers").find(".dataTables_scrollBody").scrollTop(scrollToPos);
},
show: {
effect: 'drop', direction: 'up'
},
hide: {
effect: 'fade', duration: 200
},
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
}).prev("ui-dialog-titlebar").css("cursor", "default");
This works famously.

How do I get the value from my custom widget?

The following code is a confirm dialog that contains "OK" and "Cancel" button, I would like to retrieve the value either user selected "OK" or "Cancel".
dojo.provide("custom.dialog.ConfirmDialog");
dojo.declare("custom.dialog.ConfirmDialog",dijit.Dialog , {
message : "",
postCreate: function(){
var self = this;
this.inherited(arguments);
this.contentCenter = new dijit.layout.ContentPane({ content : this.message, region: "center"});
this.contentBottom = new dijit.layout.ContentPane({region: "bottom"});
this.okButton = new dijit.form.Button( { label: "OK" } );
this.cancelButton = new dijit.form.Button( { label: "Cancel" } );
this.contentBottom.addChild(this.okButton);
this.contentBottom.addChild(this.cancelButton);
this.addChild(this.contentCenter);
this.addChild(this.contentBottom);
this.okButton.on('click', function(e){
self.emit('dialogconfirmed', { bubbles: false } );
self.destroy();
return "OK";
});
this.cancelButton.on('click', function(e){
self.emit('dialogdeclined', { bubbles: false } );
self.destroy();
return "Cancel";
});
}
});
But there was nothing returned, please help me out if you can point out my mistake, thanks!
You are trying to access the value in event listener? You can pass the label as part of the arguments.
self.emit('dialogconfirmed',
{ bubbles: false, label: self.okButton.get('label') } );
Usage:
this.confirmDialog.on('dialogconfirmed', function(data) {
var label = data.label;
});