ZXing-js/browser returns a ChecksumError no matter what QR Code I use - node.js

I'm having an issue with ZXing-js. Its returning a ChecksumException no matter what QR Code I put into it. So its detecting the QRCode but throws an Exception. The following is my vuejs 2.0 code. Please help.
Almost all if this code works. Its just the reading of the QR code part that doesn't
import { BarcodeFormat, DecodeHintType, NotFoundException, ChecksumException, FormatException } from '#zxing/library';
const ZXing = require('#zxing/browser');
Vue.component('qr_scanner_modal',{
prop: [
'videoSource'
],
data: function ()
{
return {
qr_error: null,
qrcanvas: null,
context: null,
qrvideo: null,
hints: null,
formats: null,
videoSource: {},
qr: null,
selected_source: null,
polling: null,
localMediaStream: null,
scanLineDirect: 'down',
scanlineOffset: 0,
qr_title: "",
visible: false,
focused: true,
qr_result: ""
};
},
mixins: [ focusMixin ],
created: function ()
{
EventBus.$on('trigger-qrcode-scanner', (qrTitle) => this.show(qrTitle));
},
mounted: function ()
{
let self = this;
this.$root.$on('bv::modal::show', () => this.$nextTick(() => this.mountQRReader()));
},
methods: {
mountQRReader: function ()
{
const hints = new Map();
const formats = [BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX/*, ...*/];
hints.set(DecodeHintType.POSSIBLE_FORMATS, formats);
hints.set(DecodeHintType.TRY_HARDER, true);
hints.set(DecodeHintType.CHARACTER_SET, 'UTF-8');
hints.set(DecodeHintType.ALSO_INVERTED, true);
this.qr = new ZXing.BrowserQRCodeReader(hints);
this.qrcanvas = this.$refs['qrcanvas'];
this.qrcanvas.width = 400;
this.qrcanvas.height = 400;
// this.qrcanvas = this.$refs;
console.log(this.$refs['qrcanvas']);
this.context = this.$refs['qrcanvas'].getContext('2d');
this.qrvideo = this.$refs['qrvideo'];
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices)
{
this.qr_error = "This browser does not support MediaStreamTrack. Try Chrome.";
console.log("enumerateDevices() not supported.");
}
else
{
this.qr_error = null;
}
let self = this;
navigator.mediaDevices
.enumerateDevices()
.then(function (sourceInfos)
{
let videosource = [];
for (var index = 0; index !== sourceInfos.length; index++)
{
var sourceInfo = sourceInfos[index];
if (sourceInfo.kind === 'videoinput')
{
videosource.push({
id: sourceInfo.deviceId,
name: sourceInfo.label || 'Camera ' + index
});
console.log(sourceInfo);
console.log(videosource);
}
}
self.videoSource = videosource;
})
.catch(function (err)
{
console.log(err.name + ": " + err.message);
});
},
show: function (qrTitle)
{
console.log("Show modal called.");
this.qr_title = qrTitle + " - QR / Magstripe Reader";
this.$bvModal.show('qr_code_scanner');
},
dismiss: function()
{
this.stopScan();
this.$bvModal.hide('qr_code_scanner');
},
selectSource: function (source)
{
this.selected_source = source;
let constraints = {
audio: false,
video: {
facingMode: "environment",
sourceId: source
}
};
navigator.getUserMedia(constraints, this.startScan, this.scanError);
},
read: function (value)
{
console.log('read callback called.');
console.log(value);
if (value !== null && value !== undefined)
{
this.qr_result = value.text;
EventBus.$emit('qr_code_returned', value.text);
this.stopScan();
return;
}
},
startScan: function (stream)
{
this.qrvideo.srcObject = stream;
this.localMediaStream = stream;
this.qrvideo.play();
this.polling = setInterval(this.scan, 400);
},
scanError: function (err)
{
if (err)
{
this.qr_error = err;
}
},
stopScan: function ()
{
clearInterval(this.polling);
if (this.localMediaStream)
{
let track = this.localMediaStream.getVideoTracks();
track[0].stop();
}
},
transposeRect: function (width, height)
{
const rectWidth = width * 0.8;
const rectHeight = height * 0.8;
const xPos = (width - rectWidth) / 2;
const yPos = (height - rectHeight) / 2;
this.context.beginPath();
this.context.strokeStyle = 'red';
this.context.lineWidth = '3';
this.context.rect( xPos,
yPos,
rectWidth,
rectHeight);
this.context.stroke();
this.drawScanLine(yPos,
xPos,
xPos + rectWidth,
yPos + rectHeight);
},
drawScanLine: function (top, left, right, bottom)
{
if (this.scanLineDirect === 'down')
{
this.scanlineOffset = this.scanlineOffset + 4;
}
if (this.scanLineDirect === 'up')
{
this.scanlineOffset = this.scanlineOffset - 4;
}
if (top + this.scanlineOffset > bottom)
{
this.scanLineDirect = 'up';
this.scanlineOffset = this.scanlineOffset - 4;
}
if (top + this.scanlineOffset < top)
{
this.scanLineDirect = 'down';
this.scanlineOffset = this.scanlineOffset + 4;
}
this.context.beginPath();
this.context.strokeStyle = 'red';
this.context.lineWidth = '3';
this.context.moveTo(left, top + this.scanlineOffset);
this.context.lineTo(right, top + this.scanlineOffset);
this.context.closePath();
this.context.stroke();
},
scan: async function ()
{
try
{
if (this.localMediaStream)
{
console.log("Scanning Video Feed.");
const width = this.qrcanvas.getAttribute('width');
const height = this.qrcanvas.getAttribute('height');
this.context.drawImage(this.qrvideo, 0, 0, width, height);
console.log("width: " + width);
console.log("height: " + height);
const code = await this.qr.decodeFromCanvas(this.qrcanvas);
// const code = await this.qr.decode(this.qrcanvas);
this.read(code);
this.transposeRect(width, height);
}
}
catch(err)
{
if (err instanceof NotFoundException) {
console.log('No QR code found.')
}
if (err instanceof ChecksumException) {
console.log('A code was found, but it\'s read value was not valid.')
}
if (err instanceof FormatException) {
console.log('A code was found, but it was in a invalid format.')
}
}
}
},
template: `
<b-modal id="qr_code_scanner"
v-bind:title="qr_title"
v-bind:videoSource='videoSource'
hide-footer >
<div class="alert alert-danger" v-show="qr_error != null">
{{qr_error}}
</div>
<div>
<a href='#' v-for="source in videoSource" v-on:click='selectSource(source.id)' class='btn btn-primary'>#{{source.name}}</a>
</div>
<div class="large-centered col-lg-12 col-md-12 col-sm-12" style="overflow: hidden;">
<input type="text" ref="qr_result" name='qr_result' v-focus="focused" v-model='qr_result' class="form-control" />
<video id="qrvideo" ref="qrvideo" controls="false" style="display: none;"></video>
<canvas id="qrcanvas" ref='qrcanvas' style="overflow: hidden;" width="400" height="400"></canvas>
</div>
<div class="modal-footer">
<a href='#' v-on:click='dismiss()' class='btn btn-primary'>Cancel</a>
</div>
</b-modal>
`
});
I'm expecting it to return a QR Code.

Related

API getting called multiple times

When testing the API I have noticed that it is getting called around 6 times, there is no for/foreach loop that would make it run several times in the code so am unsure as to why this may be happening.
The API runs every time a user goes onto the Landing Screen.
Any advice would be appreciated
exports.getFilteredOpportunities = async (req, res) => {
let mongoQuery = generateMongoQuery(req);
try {
const opps = await Opportunity.find(mongoQuery)
.select(removeItems)
.sort({
createdAt: -1
});
res.status(200).json({
opportunities: opps,
});
} catch (error) {
res.status(500).json({
status: "error",
message: error,
});
}
};
GenerateMongoQuery function
const generateMongoQuery = (req) => {
let query = {};
// search param used searching through Title field, ie. search=food
if (req.query.search && req.query.search.length > 0) {
query.$or = [{}, {}];
query.$or[0].Title = query.$or[1].Description = new RegExp(
`${req.query.search}`,
"i"
);
}
// location param, i.e location=Glasgow,Manchester
if (req.query.location && req.query.location.length > 0) {
query.location = {
$in: req.query.location.split(",")
};
}
// timeslot param, i.e timeslot=Evening,Morning
if (req.query.timeslot && req.query.timeslot.length > 0) {
query.timeslot = {
$in: req.query.timeslot.split(",")
};
}
// category param, returning corresponding id i.e category=
if (req.query.category && req.query.category.length > 0) {
query.category = {
$in: req.query.category.split(",")
};
}
// Dont load expired opportunities
query.eventDate = {
$gte: new Date().toDateString()
};
// Only return non-cancelled opportunities
query.isCancelled = false;
return query;
};
The landing Screen
import { useState, useEffect } from "react";
import Opportunities from "../components/molecules/Opportunities";
import Filters from "../components/organisms/Filters";
import { IOpportunity } from "../Models/IOpportunity";
import OpportunitiesClient from "../Api/opportunitiesClient";
import Utils from "../Utils/Utils";
import FiltersClient from "../Api/filtersClient";
import { IFilters } from "../Models/IFilters";
import { ISelectedFilters } from "../Models/ISelectedFilters";
import Header from "../components/atoms/Header";
import Footer from "../components/atoms/Footer";
export default function LandingScreen(props) {
const [opportunities, setOpportunities] = useState<IOpportunity[]>([]);
const [filters, setFilters] = useState<IFilters[]>([]);
const [checkedFilters, setCheckedFilters] = useState<
ISelectedFilters | undefined
>({
Location: [],
Category: [],
Timeslot: [],
});
const [isLoading, setLoading] = useState<boolean>(true);
const [allResultsLoaded, setAllResultsLoaded] = useState<boolean>(false);
let pageToGet = 1;
const [scrollPosition, setScrollPosition] = useState(0);
const [totalOpps, setTotalOpps] = useState(0);
useEffect(() => {
getOpportunities();
getFilters();
}, []);
useEffect(() => {
setTotalOpps(opportunities.length);
}, [opportunities]);
const handleScroll = () => {
setScrollPosition(window.pageYOffset);
let scrollHeight = 0;
if ((props.scrollHeight === null) !== undefined) {
scrollHeight = +props.scrollHeight;
} else {
scrollHeight = document.scrollingElement.scrollHeight;
}
if (
window.innerHeight + document.documentElement.scrollTop >=
scrollHeight
) {
if (allResultsLoaded === false) {
setLoading(true);
}
setTimeout(() => {
pageToGet += 1;
getOpportunities();
}, 600);
}
window.removeEventListener("scroll", handleScroll);
};
window.addEventListener("scroll", handleScroll, { passive: true });
const setItemChecked = (filtername: string, filterType: string) => {
// reset page and results
pageToGet = 1;
setAllResultsLoaded(false);
setCheckedFilters(
Utils.setItemChecked(filtername, filterType, checkedFilters)
);
};
const resetFilters = () => {
// reset page and results
pageToGet = 1;
setAllResultsLoaded(false);
checkedFilters.Location = [];
checkedFilters.Category = [];
checkedFilters.Timeslot = [];
getOpportunities();
};
const getFilters = () => {
FiltersClient.getAll().then((filters) => {
setFilters(filters);
});
};
const getOpportunities = () => {
console.log(opportunities);
OpportunitiesClient.getWithParams(
Utils.getAxiosParams(checkedFilters)
).then((res) => {
definePage(res);
if (opportunities.length === res["opportunities"].length)
setAllResultsLoaded(true);
setLoading(false);
});
};
const definePage = (res) => {
if (pageToGet === 1) {
setOpportunities(res["opportunities"].slice(0, 15));
} else {
setOpportunities(
opportunities.concat(
res["opportunities"].slice(
opportunities.length,
opportunities.length + 15
)
)
);
}
};
return (
<div>
<Header page="landing" includePostButton={true} />
<div
data-testid="test-div1"
className="grid md:grid-cols-[150px_auto] sm:grid-cols-1 md:grid-flow-col gap-4 mx-4 mb-5 my-10"
>
<div></div>
<div className="card-container-title">
{totalOpps} Results{" "}
{checkedFilters.Location.length > 0 ? "(Filtered)" : ""}
</div>
</div>
<div
data-testid="test-div3"
className="grid md:grid-cols-[150px_auto] sm:grid-cols-1 md:grid-flow-col gap-4 mx-4"
>
<div>
<Filters
filters={filters}
getChecked={setItemChecked}
urlCall={getOpportunities}
resetFilters={resetFilters}
checkedFilters={checkedFilters}
/>
</div>
<div
data-testid="test-div4"
className={isLoading ? "opacity-50" : ""}
>
<div className="col-span-2">
<Opportunities
items={opportunities}
isLoading={isLoading}
allResultsLoaded={allResultsLoaded}
/>
</div>
</div>
</div>
<Footer />
</div>
);
}

Generate 1000 pdf with survey pdf

I'm trying to generate more than one thousand pdf files using surveyPDF.
The problem is that i can generate only 80 pdf files...
I'm passing an array with more than 1000 pdf to generate.
Code :
query.map(async items => {
const { generatePdf } = await import("~/lib/survey");
const filename = kebabCase(
`${campaign.title} - ${items.employee.fullName.toLowerCase()} -${moment().format("DD/MM/YYYY - HH:mm")} `
);
return generatePdf(campaign.template.body, items, filename, 210, 297);
});
The code which generate each pdfs :
import autoTable from "jspdf-autotable";
import { SurveyPDF, CommentBrick, CompositeBrick, PdfBrick, TextBrick } from "survey-pdf";
import { format } from "~/utils/date";
class AutoTableBrick extends PdfBrick {
constructor(question, controller, rect, options) {
super(question, controller, rect);
this.margins = {
top: controller.margins.top,
bottom: controller.margins.bot,
right: 30,
left: 30,
};
this.options = options;
}
renderInteractive() {
if (this.controller.doc.lastAutoTable && !this.options.isFirstQuestion) {
this.options.startY = this.yTop;
}
autoTable(this.controller.doc, {
head: [
[
{
content: this.question.title,
colSpan: 2,
styles: { fillColor: "#5b9bd5" },
},
],
],
margin: { ...this.margins },
styles: { fillColor: "#fff", lineWidth: 1, lineColor: "#5b9bd5", minCellWidth: 190 },
alternateRowStyles: { fillColor: "#bdd6ee" },
...this.options,
});
}
}
export async function generatePdf(json, data, filename, pdfWidth, pdfHeight) {
if (!json) {
return Promise.reject("Invalid json for pdf export");
}
for (const page of json.pages) {
page.readOnly = true;
}
const surveyPDF = new SurveyPDF(json, {
fontSize: 11,
format: [pdfWidth, pdfHeight],
commercial: true,
textFieldRenderAs: "multiLine",
});
surveyPDF.showQuestionNumbers = "off";
surveyPDF.storeOthersAsComment = false;
//TODO This does not work well with dynamic dropdown, bug declared
// surveyPDF.mode = "display";
surveyPDF.mergeData({ ...data, _: {} });
surveyPDF.onRenderQuestion.add(function(survey, options) {
const { bricks, question } = options;
if (question.getType() === "comment" && question.value && bricks.length > 0) {
for (const brick of bricks) {
if (brick.value) {
brick.value = question.value.replace(/\t/g, " ");
}
if (brick instanceof CompositeBrick) {
const { bricks } = brick;
for (const brick of bricks) {
if (brick instanceof CommentBrick) {
brick.value = question.value.replace(/\t/g, " ");
}
}
}
}
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
bricks,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "multipletext") {
const body = [];
let extraRows = 0;
let rows = question.getRows();
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
let { title, value, inputType } = rows[i][j];
if (inputType === "date") {
value = format(value);
}
if (typeof value === "string" && value.length > 0) {
const valueEstRows = value.match(/.{1,70}/g).length;
if (valueEstRows > 1) {
extraRows += valueEstRows;
}
}
body.push([title, value || "N/A"]);
}
}
//TODO Use SurveyHelper helperDoc do calculate the height of the auto table
const startY = point.yTop;
const height = 21.5 * (body.length + 1) + 8.5 * extraRows;
const isFirstQuestion = question.title === question.parent.questions[0].title;
options.bricks = [
new AutoTableBrick(question, controller, SurveyHelper.createRect(point, bricks[0].width, height), {
startY,
body,
isFirstQuestion,
}),
];
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "text") {
//Draw question background
const { default: backImage } = await import("~/public/assets/images/block.png");
const backWidth = SurveyHelper.getPageAvailableWidth(controller);
const backHeight = SurveyHelper.pxToPt(100);
const imageBackBrick = SurveyHelper.createImageFlat(point, null, controller, backImage, backWidth, backHeight);
options.bricks = [imageBackBrick];
point.xLeft += controller.unitWidth;
point.yTop += controller.unitHeight;
const oldFontSize = controller.fontSize;
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
//Draw text question text field border
let { default: textFieldImage } = await import("~/public/assets/images/input.png");
let textFieldPoint = SurveyHelper.createPoint(imageBackBrick);
textFieldPoint.xLeft += controller.unitWidth;
textFieldPoint.yTop -= controller.unitHeight * 3.3;
let textFieldWidth = imageBackBrick.width - controller.unitWidth * 2;
let textFieldHeight = controller.unitHeight * 2;
let imageTextFieldBrick = SurveyHelper.createImageFlat(
textFieldPoint,
null,
controller,
textFieldImage,
textFieldWidth,
textFieldHeight
);
options.bricks.push(imageTextFieldBrick);
textFieldPoint.xLeft += controller.unitWidth / 2;
textFieldPoint.yTop += controller.unitHeight / 2;
let textFieldValue = question.value || "";
if (textFieldValue.length > 90) {
textFieldValue = textFieldValue.substring(0, 95) + "...";
}
const textFieldBrick = await SurveyHelper.createBoldTextFlat(
textFieldPoint,
question,
controller,
textFieldValue
);
controller.fontSize = oldFontSize;
textFieldBrick.unfold()[0]["textColor"] = "#EFF8FF";
options.bricks.push(textFieldBrick);
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "radiogroup" || question.getType() === "rating") {
options.bricks = [];
const oldFontSize = controller.fontSize;
const titleLocation = question.hasTitle ? question.getTitleLocation() : "hidden";
let fieldPoint;
if (["hidden", "matrix"].includes(titleLocation)) {
fieldPoint = SurveyHelper.clone(point);
} else {
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
titleBrick.xLeft += controller.unitWidth;
titleBrick.yTop += controller.unitHeight * 2;
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
fieldPoint = SurveyHelper.createPoint(titleBrick);
fieldPoint.yTop += controller.unitHeight * 1.3;
}
//Draw checkbox question items field
const { default: itemEmptyImage } = await import("~/public/assets/images/unchecked.png");
const { default: itemFilledImage } = await import("~/public/assets/images/checked.png");
const itemSide = controller.unitWidth;
let imageItemBrick;
const choices = question.getType() === "rating" ? question.visibleRateValues : question.visibleChoices;
for (const choice of choices) {
const isItemSelected =
question.getType() === "rating" ? question.value === choice.value : choice === question.selectedItem;
imageItemBrick = SurveyHelper.createImageFlat(
fieldPoint,
null,
controller,
isItemSelected ? itemFilledImage : itemEmptyImage,
itemSide,
itemSide
);
options.bricks.push(imageItemBrick);
const textPoint = SurveyHelper.clone(fieldPoint);
textPoint.xLeft += itemSide + controller.unitWidth / 2;
textPoint.yTop += itemSide / 12;
const itemValue = choice.locText.renderedHtml;
const checkboxTextBrick = await SurveyHelper.createTextFlat(
textPoint,
question,
controller,
itemValue,
TextBrick
);
checkboxTextBrick.unfold()[0]["textColor"] = "#6a6772";
fieldPoint.yTop = imageItemBrick.yBot + SurveyHelper.GAP_BETWEEN_ROWS * controller.unitHeight;
options.bricks.push(checkboxTextBrick);
}
}
});
surveyPDF.onRenderFooter.add(function(survey, canvas) {
canvas.drawText({
text: canvas.pageNumber + "/" + canvas.countPages,
fontSize: 10,
horizontalAlign: "right",
margins: {
right: 12,
},
});
});
return await surveyPDF.raw(`./pdf/${filename}.pdf`);
}
The error :
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
I have already try to increase the node memory using $env:NODE_OPTIONS="--max-old-space-size=8192"

How to fix/trouble shoot the missing response from nodejs service?

I am trying to trouble shoot/fix my nodejs upload image api:
My service is being stuck at somewhere.
My service is too simple, just uploading the image by resizing through sharp api in a directory and return the full path of that file.
When I select some image at first time then everything works fine and image upload successfully with a response
but When I try to crop that image after clicking on the image and try to save it (at second time) then nodejs service return following response.
I don't why it is being happened, I tried to debug the service code and It didn't stop at anywhere. Flow has been passed/executed successfully, I didn't catch any exception/error in code.
What can be the issue in it because it still displaying
> Blockquote failed to load response data. no resource with given identifier found
Problem area is in the code of onSaveImage when a server side call is being served/requested. I am using the plugin for image cropping is react-easy-crop. Browser is getting refresh/reload at this line of code
const jsonRes = await responseMain.json();
I am sharing my nodejs service code as well as reactjs code. please look into it.
Thank you.
-----------------package.json of nodejs
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-validator": "^6.12.0",
"handlebars": "^4.7.7",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.18.1",
"nodemailer": "^6.6.1",
"nodemon": "^2.0.12",
"sharp": "^0.29.3"
},
"devDependencies": {},
"scripts": {
"start": "nodemon --inspect index.js",
"debug": "node --nolazy --inspect-brk=9229 index.js"
},
"license": "ISC"
}
------ index.js---------------------------NodeJs
const express = require("express");
const app = express();
const cors = require("cors");
var fs = require("fs");
const fsp = fs.promises;
var path = require("path");
const sharp = require("sharp");
var $pathContentBuilder = path.join(__dirname, "../", "/public/roughdata/uploads/");
var $urlpathContentBuilder = "/roughdata/uploads/"; // URL path
app.use(express.json({ limit: "20mb" }));
app.use(cors());
app.use(
express.urlencoded({
extended: true,
})
);
function processImage(image, metadata, filename, isResizeAllow) {
return new Promise((resolve, reject) => {
if (isResizeAllow && isResizeAllow === true) {
// 0.8 MB
return image
.resize({
width: Math.round(metadata.width / 2),
height: Math.round(metadata.height / 2),
fit: "cover",
})
.toBuffer((err, buf) => {
if (err) {
console.log("Error occured ", err);
return reject(err);
} else {
return resolve(buf.toString("base64"));
}
});
} else {
return image.toBuffer((err, buf) => {
if (err) {
console.log("Error occured ", err);
return reject(err);
} else {
return resolve(buf.toString("base64"));
}
});
}
});
}
app.post("/uploaddetail", async (req, res, next) => {
const base64Data = req.body.image;
const filename = req.body.filename;
let imageResizeResult = "";
try {
var inputbuf = Buffer.from(base64Data, "base64"); // Ta-da
const image = await sharp(inputbuf);
let metadata = await image.metadata();
let convertedbase64Data = "";
convertedbase64Data = await processImage(image, metadata, filename, false);
await fsp.writeFile($pathContentBuilder + filename, convertedbase64Data, "base64");
let resultResponse = JSON.stringify({
success: true,
fullurl: `${$urlpathContentBuilder}${filename}`,
url: `${filename}`,
imagename: `${filename}`,
serverpath: `${$urlpathContentBuilder}`,
});
//res.type("json");
res.status(200).json(resultResponse);
//res.end();
//next();
} catch (e) {
console.log(e);
const error = new HttpError(e, 404);
return next(error);
}
});
and following is my reactjs code.
import React, { useState, useEffect, useCallback } from "react";
import { withRouter, useParams, useHistory } from "react-router-dom";
import { Card, Button } from "react-bootstrap";
import Page from "./Page";
import TitleBar from "./TitleBar";
import SingleGalleryRow from "./SingleGalleryRow";
import CenteredPopup from "../common/CenteredPopup";
import { MdDelete, MdOutlineCrop, MdOutlineCircle } from "react-icons/md";
import Cropper from "react-easy-crop";
import getCroppedImg from "../shared/util/cropImage";
import b64toBlob from "../shared/util/blobToImage";
function EditImage({ breadcrumb, pageName, setLoader, showToast }) {
const [list, setList] = useState([]);
const history = useHistory();
const [umodalShow, setUModalShow] = useState(false);
const [row, setRow] = useState({
ImageName: "",
ImageServerPath: "",
ImageFullUrl: "",
ImageUrl: "",
SiteId: 1,
CreatedBy: 1,
CreatedOn: "",
Id: 0,
Name: "",
IsDeleted: 0,
IsVisible: 1,
ModifiedBy: 1,
ModifiedOn: "",
});
const [isSubmitClicked, setIsSubmitClicked] = useState(false);
const [IsDisabled, setIsDisabled] = useState(false);
const [nameError, setNameError] = useState("");
const [validated, setValidated] = useState(0);
const [ImageName, setImageName] = useState("");
const [base64SelectedImage, setBase64SelectedImage] = useState("");
const { id } = useParams();
let content = "";
const [detail, setDetail] = useState({
Content: "",
CreatedBy: 1,
CreatedOn: "",
Id: 0,
IsDeleted: 0,
IsVisible: 1,
ModifiedBy: 1,
ModifiedOn: "",
Name: "",
SiteId: 1,
});
useEffect(() => {
let abortController = new AbortController();
let mounted = true;
const fetchData = async () => {
try {
setLoader(true);
let apiUrl = process.env.REACT_APP_IMAGEGALLERYAPI + "/getbyId/" + id;
const response = await fetch(apiUrl, {
signal: abortController.signal,
});
const json = await response.json();
const resultPages = json ? json.list : "";
if (resultPages && resultPages.length > 0) {
//debugger;
let firstRow = resultPages[0];
let isEnabled = false;
if (firstRow.IsVisible === 1 || firstRow.IsVisible === true) {
isEnabled = true;
}
let newDetailPage = {
Id: firstRow.Id,
Name: firstRow.Name,
Content: firstRow.Content
};
if (mounted) {
setDetail(newDetailPage);
}
let itemRows = [];
for (let item of resultPages) {
let row = {
Id: item.DetailId,
ImageSliderId: item.ImageSliderId,
ImageName: item.ImageName,
ImageFullUrl: item.ImageFullUrl,
};
if (item.ImageFullUrl) {
itemRows.push(row);
}
}
if (itemRows && itemRows.length > 0) {
if (mounted) {
setList(itemRows);
}
}
}
setLoader(false);
//abortController = null;
} catch (err) {
setLoader(false);
if (err.name === "AbortError") {
// Handling error thrown by aborting request
}
}
};
fetchData();
// Side-effect logic...
return () => {
// Side-effect cleanup
mounted = false;
abortController.abort();
console.log("unmounting...");
};
}, []);
const [imageCropWidth, setImageCropWidth] = useState(100);
const [imageCropHeight, setImageCropHeight] = useState(100);
const [crop, setCrop] = useState({ x: 0, y: 0 });
const [zoom, setZoom] = useState(1);
const [aspect, setAspect] = useState(1);
const [croppedAreaPixels, setCroppedAreaPixels] = useState(null);
const [croppedImage, setCroppedImage] = useState(null);
const [cropSize, setCropSize] = useState({ width: 100, height: 100 });
const [Image, setImage] = useState("");
const [rotation, setRotation] = useState(0);
const [cropShape, setCropShape] = useState("rect");
const onSaveImage = useCallback(
async (e) => {
e.preventDefault();
if (validate() < 0) {
return -1;
}
try {
let filename = "";
let base64Image = "";
let blobUrl = "";
debugger;
const cropImage = await getCroppedImg(Image, croppedAreaPixels, rotation);
setCroppedImage(cropImage);
setImage(cropImage);
base64Image = cropImage ? cropImage.replace(/^data:image\/(png|jpeg);base64,/, "") : "";
const contentType = "image/jpeg";
if (cropImage) {
debugger;
setRow((prevState) => {
return {
...prevState,
["ImageFullUrl"]: cropImage,
["ImageName"]: ImageName ? ImageName : "",
};
});
filename = ImageName ? ImageName : "";
const settings = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
filename: filename,
image: base64Image,
}),
};
setLoader(true);
let submitUrl = process.env.REACT_APP_SERVER_DOMAIN + `/uploaddetail`;
const responseMain = await fetch(submitUrl, settings);
const jsonRes = await responseMain.json();
if (jsonRes) {
let convertedJson = jsonRes;
if (convertedJson) {
setLoader(false);
const uploadedImageUrl = convertedJson.fullurl; // get saved image url
const uploadedImageName = convertedJson.imagename;
const uploadedServerPath = convertedJson.serverpath;
const uploadurl = convertedJson.url;
setImageName(convertedJson.imagename);
setRow((prevState) => {
return {
...prevState,
["ImageName"]: uploadedImageName,
["ImageServerPath"]: uploadedServerPath,
["ImageFullUrl"]: uploadedImageUrl,
["ImageUrl"]: uploadurl,
};
});
if (uploadedImageUrl) {
setIsDisabled(false);
}
setUModalShow(false);
setDetail((prevState) => {
return {
...prevState,
["Content"]: content,
};
});
}
}
}
} catch (err) {
console.log(err);
showToast("Error!", "Image couldn't be saved");
} finally {
}
},
[croppedAreaPixels, rotation]
);
const showImageForCrop = useCallback(
async (e) => {
debugger;
let localSrc = e.ImageFullUrl; //e.target.src;
setImage(localSrc);
setUModalShow(true);
setImageName(e.ImageName);
setCropSize({ width: imageCropWidth ? parseInt(imageCropWidth) : 0, height: imageCropHeight ? parseInt(imageCropHeight) : 0 });
if (list && list.length > 0) {
const selectedIndex = list.findIndex((item) => item.Id === e.Id);
if (selectedIndex > -1) {
setRow(list[selectedIndex]);
}
}
},
[row]
);
const singlefileSelectedHandler = async (e) => {
//debugger;
e.preventDefault();
setIsDisabled(true);
content = "";
if (!e.target.files || e.target.files.length <= 0) {
return -1;
}
if (detail && detail.Content) {
content = detail.Content;
}
//let imageList = "";
const selectedImage = e.target.files[0];
let imageSizeInMBs = selectedImage.size ? selectedImage.size / 1024 / 1024 : 0;
if (selectedImage && imageSizeInMBs > 8) {
setIsDisabled(false);
setRow((prevState) => {
return {
...prevState,
["ImageName"]: "",
["ImageServerPath"]: "",
["ImageFullUrl"]: "",
["ImageUrl"]: "",
};
});
showToast("Information!", "Image size can't be greater than 8MB.");
return -1;
}
const filename =
selectedImage && selectedImage.name
? new Date().valueOf() +
"_" +
selectedImage.name.replace(/\\/g, "").replace(/ /g, "").replace(/'/g, "").replace(/"/g, "").replace(/`/g, "")
: "";
setUModalShow(false);
setCropSize({ width: imageCropWidth ? parseInt(imageCropWidth) : 0, height: imageCropHeight ? parseInt(imageCropHeight) : 0 });
setImageName(filename);
setUModalShow(true);
let convertedImageFile = await convertImage(selectedImage);
setBase64SelectedImage(convertedImageFile);
};
async function convertImage(file) {
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
e.preventDefault();
let base64 = e.target.result;
base64 = base64.replace(/^data:image\/(png|jpeg);base64,/, "");
setImage(reader.result);
resolve(base64);
//resolve(reader.result);
};
reader.onerror = function (error) {
console.log("Error: ", error);
reject(error);
};
});
}
const onAddSide = (e) => {
//debugger;
let newImageList = [...list];
if (row.Id && row.Id > 0) {
if (newImageList && newImageList.length > 0) {
const selectedIndex = newImageList.findIndex((item) => item.Id === row.Id);
if (selectedIndex > -1) {
newImageList[selectedIndex] = row;
}
}
} else {
row.Id = Math.max.apply(
Math,
newImageList.map(function (o) {
return o.Id + 1;
})
);
if (!row.Id || (row.Id && row.Id === 0) || row.Id === -Infinity) {
row.Id = 1;
}
newImageList.push(row);
}
setList(newImageList);
};
const onCropComplete = useCallback((croppedArea, croppedAreaPixels) => {
//debugger;
setCroppedAreaPixels(croppedAreaPixels);
}, []);
const onClose = useCallback(() => {
setCroppedImage(null);
}, []);
const onCropperZoomChange = (e) => {
if (e && e.currentTarget && e.currentTarget.value) {
let lZoomValue = e.currentTarget.value;
if (lZoomValue && lZoomValue < 0.4) {
//setZoom(0.28);
setZoom(0.4);
} else if (lZoomValue && lZoomValue > 1) {
setZoom(1);
} else {
setZoom(lZoomValue);
}
}
};
return (
<Page breadcrumb={breadcrumb} pageName={pageName} fluid>
<form noValidate validated={validated} onSubmit={HandleSaveMenu} className="user-form">
<Card>
<Card.Header>
<TitleBar title="Edit Gallery" />
</Card.Header>
<Card.Body>
<div className="form-row">
<div className="form-group col-md-2">
<label className="form-label" htmlFor="ImageCropWidth">
Width
</label>
<input
name="ImageCropWidth"
id="ImageCropWidth"
className={`form-control`}
value={imageCropWidth}
onChange={(e) => setImageCropWidth(e.target.value)}
/>
</div>
<div className="form-group col-md-2">
<label className="form-label" htmlFor="ImageCropWidth">
Height
</label>
<input
name="ImageCropWidth"
id="ImageCropWidth"
className={`form-control`}
value={imageCropHeight}
onChange={(e) => setImageCropHeight(e.target.value)}
/>
</div>
</div>
<SingleGalleryRow
data={row}
setRow={setRow}
onUpload={singlefileSelectedHandler}
onAddSide={onAddSide}
IsDisabled={IsDisabled}
/>
<ul className="slide-list">
{list &&
list.map(function (item, i) {
//debugger;
return (
<li key={i}>
<div className="slide-row">
<div className="img-holder">
<img
className="thumbnail"
src={item.ImageFullUrl}
alt={item.ImageName}
onClick={() => showImageForCrop(item)}
/>
</div>
</div>
</li>
);
})}
</ul>
</Card.Body>
<Card.Footer>
<div className="btn-holder text-right">
<Button type="submit" variant="primary" disabled={isSubmitClicked}>
Save
</Button>
</div>
</Card.Footer>
</Card>
</form>
<CenteredPopup
show={umodalShow}
onHide={() => setUModalShow(false)}
title="Crop Image"
content=""
closetext="Close"
savetext="Apply"
onSaveChanges={onSaveImage}
>
<div className="cropimage-container">
<div className="cropimage-tools">
<span className="cropimage-icons" onClick={(e) => setCropShape("rect")}>
<MdOutlineCrop />
<span className="cropimage-text">Crop</span>
</span>
<span className="cropimage-icons" onClick={(e) => setCropShape("round")}>
<MdOutlineCircle />
<span className="cropimage-text">Circle</span>
</span>
</div>
<div className="crop-container">
<Cropper
image={Image}
crop={crop}
cropSize={cropSize}
cropShape={cropShape}
zoom={zoom || 1}
showGrid={true}
zoomWithScroll={false}
objectFit="horizontal-cover"
onCropChange={setCrop}
onCropComplete={onCropComplete}
onZoomChange={onCropperZoomChange}
/>
</div>
</div>
<div className="form-row ic_rangeslider">
<div className="form-group col-md-12">
<label className="form-label" htmlFor="ZoomBtn">
{zoom || 1}
</label>
<span className="range-slider__wrap">
<input
id="zoomrangeid"
type="range"
className="slider range-slider range-slider--light"
value={zoom || 1}
min={0.4}
max={1}
step={0.1}
aria-labelledby="Zoom"
onChange={onCropperZoomChange}
/>
</span>
</div>
</div>
</CenteredPopup>
</Page>
);
}
export default withRouter(EditImage);

Js Phaser 3 game window not displaying

I'm fairly new to Phaser 3, and I just started dipping my feet in scenes. The problem here is that the game window won't display, and I can't figure out why.
Leaving my entire code here just in case there's a problem somewhere else. Sorry about the wall of text. Any help would be appreciated, even if it isn't a direct fix.
class scene1 extends Phaser.Scene{
constructor() {
super({ key: 'scene1' });
this.pause = false;
this.q = null;
this.player = null;
this.roundTxt = null;
this.handUp = true;
this.round = 1;
this.flash = true;
this.platforms = null;
this.hudStar = null;
this.starCountTxt = null;
this.bombs = null;
this.left = false;
this.lives = 3;
this.hudLives = null;
this.starCount = 0;
this.gameOver = false;
this.bCol = null;
this.pCol = null;
this.invincible = false;
this.invFlash = null;
this.tw = null;
this.slam = false;
this.bullets = null;
this.keySpace = null;
this.shot = false;
this.game = new Phaser.Game(config);
this.direction = 1;
this.bombs = null;
this.bullets = new Bullets(this);
this.cursors = this.input.keyboard.createCursorKeys();
//initialize stars
this.stars = this.physics.add.group({
key: 'star',
repeat: 9,
setXY: { x: 12, y: 0, stepX: 80 },
});
// Define spacebar
this.keySpace = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
this.window.bullets = this.bullets;
}
addBomb() {
var x = Phaser.Math.Between(0, 800);
var y = Phaser.Math.Between(30, 450);
this.bombs.children.iterate(function (child) {
x = Phaser.Math.Between(0, 800);
y = Phaser.Math.Between(30, 450);
if (child.active) {
child.enableBody(true, child.x, child.y, true, true);
} else {
child.enableBody(true, x, y, true, true);
}
child.setVelocityX(50 * Phaser.Math.Between(10, 2));
child.setVelocityY(50 * Phaser.Math.Between(10, 2));
});
x = Phaser.Math.Between(0, 800);
y = Phaser.Math.Between(30, 450);
scene1.bomb = this.bombs.create(x, y, 'bomb').setBounce(1).setCollideWorldBounds(true).setVelocityX(50 * Phaser.Math.Between(10, 2)).setVelocityY(50 * Phaser.Math.Between(10, 2));
}
preload () {
this.load.image('sky', 'assets/tut/sky.png');
this.load.image('ground', 'assets/tut/platform.png');
this.load.image('star', 'assets/tut/star.png');
this.load.image('bomb', 'assets/tut/bomb.png');
this.load.spritesheet('dude', 'assets/tut/dude.png', { frameWidth: 32, frameHeight: 48 });
this.load.image('life', 'assets/tut/dudeLife.png');
this.load.image('bullet', 'assets/bullet7.png');
}
//end preload
//create
create () {
//add sky background
this.add.image(400, 300, 'sky');
//add player
this.player = this.physics.add.sprite(100, 450, 'dude');
//player bounces
//set world bounds
this.player.setCollideWorldBounds(true);
//animations
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [ { key: 'dude', frame: 4 } ],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
//create group 'platforms'
this.platforms = this.physics.add.staticGroup();
//add ground platforms
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
//add sky platforms
this.platforms.create(600, 400, 'ground');
this.platforms.create(50, 250, 'ground');
this.platforms.create(750, 220, 'ground');
//cursors
//add stars
this.stars.children.iterate(function(child) {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
child.setCollideWorldBounds(true);
});
//set bombs
this.bombs = this.physics.add.group();
this.addBomb();
//collision
this.pCol = this.physics.add.collider(this.player, this.platforms);
this.physics.add.collider(this.stars, this.platforms);
this.physics.add.collider(this.stars, this.bombs);
this.physics.add.collider(this.bombs, this.platforms);
this.bCol = this.physics.add.collider(this.player, this.bombs, hitBomb, null, this);
this.physics.add.overlap(this.player, this.stars, collectStar, null, this);
function collectStar(player, star) {
scene1.star.disableBody(true, true);
scene1.starCount++;
if (scene1.stars.countActive(true) === 0) {
scene1.flash = true;
scene1.round++;
scene1.bCol.active = false;
scene1.stars.children.iterate(function (child) {
child.enableBody(true, child.x, 0, true, true);
});
scene1.addBomb();
}
}
//function for player/bomb col
function hitBomb(player, bomb) {
if (scene1.slam) {
bomb.disableBody(true, true);
player.setVelocityY(-300);
} else {
if (scene1.invincible == false) {
scene1.bCol.active = false;
bomb.disableBody(true, true);
scene1.invincible = true;
scene1.lives--;
if (scene1.lives == 2) {
scene1.hudLives.three.destroy();
} else if (scene1.lives == 1) {
scene1.hudLives.two.destroy();
} else {
scene1.gameOver = true;
scene1.hudLives.one.destroy();
}
player.setAlpha(0);
scene1.add.tween({
targets: player,
alpha: 1,
duration: 100,
ease: 'Linear',
repeat: 5,
onComplete: function() {
scene1.invincible = false;
scene1.bCol.active = true;
}
});
}
}
}
// bullets = new Bullet(this);
this.physics.add.overlap(scene1.bullets, scene1.bombs, scene1.shootBomb, null, this );
//define pause button
this.q = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q);
/////////////////////////
/////////////////////////
/////////////////////////
//////////HUD////////////
/////////////////////////
/////////////////////////
scene1.starCountTxt = this.add.text(35, 10, scene1.starCount, { font: ' 20px sans-serif', fill: '#ffffff' });
//star hud img
scene1.hudStar = this.add.image(20, 20, 'star');
//adds lives on hud
scene1.hudLives = {
one: this.add.image(20, 90, 'life'),
two: this.add.image(30, 90, 'life'),
three: this.add.image(40, 90, 'life')
};
scene1.roundTxt = {
label: this.add.image(20, 55, 'bomb'),
num: this.add.text(35, 43, scene1.round, { font: '20px sans-serif', fill: '#ffffff'})
};
//end of create
} //this curly bracket
//end of create
update () {
scene1.roundTxt.num.setText(scene1.round);
if (scene1.bombs.countActive(true) == 0) {
scene1.addBomb();
scene1.flash = true;
scene1.round++;
}
if (scene1.flash) {
scene1.flash = false;
scene1.bCol.active = false;
scene1.bombs.children.iterate(function(child) {
child.setTint(0x00ff00);
setTimeout(function(){
child.setTint(0xffffff);
scene1.bCol.active = true;
}, 1000);
});
}
if (scene1.cursors.left.isDown) {
scene1.direction = -1;
}
else if (scene1.cursors.right.isDown) {
scene1.direction = 1;
}
scene1.starCountTxt.setText(scene1.starCount);
if (scene1.gameOver) {
this.physics.pause();
scene1.player.setTint(0xff0000);
scene1.player.anims.play('turn');
var die = this.add.tween({
targets: scene1.player,
scaleX: '-=0.5',
scaleY: '-=0.5',
angle: '-=360',
repeat: 1,
duration: 500,
onComplete: function() {
die.delete();
}
});
}
if (scene1.cursors.left.isDown) {
scene1.player.setVelocityX(-300);
scene1.left = true;
scene1.player.anims.play('left', true);
}
else if (scene1.cursors.right.isDown) {
scene1.player.setVelocityX(300);
scene1.left = false;
scene1.player.anims.play('right', true);
}
else {
scene1.player.setVelocityX(0);
scene1.player.anims.play('turn');
}
if (scene1.cursors.up.isDown && scene1.player.body.touching.down) {
scene1.player.setVelocityY(-400);
}
if (scene1.cursors.down.isDown && scene1.player.body.touching.down && scene1.player.y < 500) {
if (!scene1.slam) {
scene1.player.y += 5;
scene1.slam = true;
}
} else if (scene1.player.body.touching.down == false && scene1.cursors.down.isDown) {
if (!scene1.slam) {
scene1.player.setVelocityY(1000);
scene1.slam = true;
}
} else if (scene1.cursors.down.isDown == false) {
scene1.slam = false;
}
if (scene1.player.body.velocity.y < 0) {
scene1.pCol.active = false;
} else {
scene1.pCol.active = true;
}
if (scene1.keySpace.isDown) {
if (!scene1.shot && scene1.handUp) {
this.bullets.fireBullet(scene1.player.x, scene1.player.y+5);
console.log(this.bullets);
scene1.shot = true;
this.tweens.addCounter({
from: 50,
to: 200,
duration: 200,
onUpdate: function (tween)
{
var value = Math.floor(tween.getValue());
scene1.player.setTint(Phaser.Display.Color.GetColor(value, value, value));
}
});
this.time.delayedCall(300, function(){
scene1.shot = false;
scene1.player.setTint(0xffffff);
}, [], this);
}
scene1.handUp = false;
}
if (scene1.keySpace.isUp) {
scene1.handUp = true;
}
if (Phaser.Input.Keyboard.JustDown(scene1.q)) {
if (scene1.pause) {
this.physics.resume();
scene1.pause = false;
} else {
this.physics.pause();
scene1.pause = true;
}
}
//end of update
} //this curly bracket
//end of update
shootBomb(bullets, bombs) {
bombs.disableBody(true, true);
bullets.disableBody(true, true);
}
}
class Bullet extends Phaser.Physics.Arcade.Sprite {
constructor(scene1, x, y) {
super(scene1, x, y, 'bullet');
}
fire(x, y) {
this.body.reset(x, y);
this.setVelocityX(1000 * scene1.direction);
this.enableBody();
this.body.setAllowGravity(false);
this.setActive(true);
this.setVisible(true);
}
preUpdate(time, delta) {
super.preUpdate(time, delta);
// Reset the bullets when it reaches end of screen
if (this.x > 2600) {
this.setActive(false);
this.setVisible(false);
}
}
}
class Bullets extends Phaser.Physics.Arcade.Group {
constructor(scene) {
super(scene.physics.world, scene);
this.createMultiple({
frameQuantity: 20,
key: 'bullet',
active: false,
visible: false,
classType: Bullet
});
}
fireBullet(x, y) {
let bullet = this.getFirstDead(false);
if (bullet) {
bullet.fire(x, y);
}
}
}
var config = {
type: Phaser.GAME,
width: 800,
height: 600,
parent: 'gameDiv',
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: [scene1],
debug: true
};
When configuring the game you're asking it to load inside of an element with an id of gameDiv, by using parent on the game configuration.
var config = {
type: Phaser.GAME,
width: 800,
height: 600,
parent: 'gameDiv',
// ...
};
If the game isn't displaying at all, that suggests that it may not be able to find an element with the id of gameDiv.
Can you verify that an element (typically a div, so <div id="gameDiv"></div>) exists in your HTML file?

How to create Pagination with vue-table2?

I'm using the Vue-table2 for rendering the table. https://github.com/ratiw/vuetable-2
<vuetable ref="vuetable"
:api-url= "apiurl"
:fields="fields">
</vuetable>
My Server Api Response doesn't have any Pagination response in it . The data returned by server is
{
"data":[
{
"id":22535,
"message":"Message1",
"message_type":"tag1",
"time":"2018-08-13T14:41:57Z",
"username":"rahuln"
},
{
"id":22534,
"message":"Message2",
"message_type":"tag2",
"time":"2018-08-13T14:02:27Z",
"username":"govindp"
},
..................
],
"error":null,
"success":true
}
This is the first time I'm Using Vue-js. How can i add the pagination into it and still using vue-table2.
Thanks In advance.
Since you don't have pagination values you must insert it we gonna trick vue-table like this
<template>
<div>
<vuetable ref="vuetable" api-url="/api/ahmed" :fields="fields" pagination-path="" #vuetable:pagination-data="onPaginationData" #vuetable:load-success="loadSuccess">
</vuetable>
<vuetable-pagination ref="pagination" #vuetable-pagination:change-page="onChangePage"></vuetable-pagination>
</div>
</template>
<script>
import Vuetable from 'vuetable-2/src/components/Vuetable'
import VuetablePagination from 'vuetable-2/src/components/VuetablePagination'
export default {
components: {
Vuetable,
VuetablePagination,
},
data() {
return {
fields: ['name', 'email', 'birthdate', 'nickname', 'gender', '__slot:actions'],
allData: false,
currentPage: 1,
}
},
mounted() {
},
methods: {
onPaginationData(paginationData) {
this.$refs.pagination.setPaginationData(paginationData)
},
loadSuccess(data) {
this.$refs.vuetable.$nextTick(()=>{
if (!this.allData) {
this.allData = data;
}
if (!data.data.per_page) {
data = this.setData(this.currentPage);
this.$refs.vuetable.loadSuccess(data);
}
})
},
setData(Page) {
var data = JSON.parse(JSON.stringify(this.allData));
var total = data.data.data.length;
var perPage = 10;
var currentPage = Page;
var lastPage = parseInt(total / perPage) + ((total % perPage) === 0 ? 0 : 1)
var from = parseInt((currentPage - 1) * perPage) + 1;
var to = from + perPage - 1;
to = to > total ? total : to;
console.log(from,to)
var newData = this.allData.data.data.filter(function(element, index) {
if (index >= from-1 && index <= to-1) {
console.log(index,from,to)
return true;
}
return false;
})
// console.log(newData)
// return newData;
data.data = {
"total": total,
"per_page": perPage,
"current_page": currentPage,
"last_page": lastPage,
"next_page_url": "",
"prev_page_url": null,
"from": from,
"to": to,
data: newData
}
// console.log(data)
this.currentPage = Page;
this.$refs.vuetable.loadSuccess(data);
return data;
},
onChangePage(page) {
this.setData(page);
}
}
}
</script>

Resources