Vue. Js Laravel count elements of JSON - json

I would like to display the number of tasks elements in JSON, but I do not know how to go about it.
I want to make something like this:
Tasks to do 2/12 (where 2 - tasks with flag 1, 12 - all tasks)
I tried using the lenght function, but I got the information function lenght is not defined, similarly with the slice function.
[
{
"id":1,
"clients_id":1,
"products_id":1,
"tasks_id":1,
"project_name":"Some project",
"created_at":null,
"updated_at":null,
"clients":{
"id":1,
"client_name":"Some client",
"contact_name":"Some client",
"client_phone":"123123123",
"client_mail":"clientmail#mailclient.com",
"client_nip":"1112223333",
"client_logo":"logo.jpg",
"updated_at":"2019-04-11 09:45:11",
"created_at":"-0001-11-30 00:00:00"
},
"products":{
"id":1,
"product_name":"Some product",
"product_description":"Really nice product bro",
"product_price":"999$",
"updated_at":"2019-04-08 14:35:13",
"created_at":null
},
"tasks":[
{
"id":1,
"project_id":1,
"task_name":"First task",
"task_description":"its very hard task",
"task_due":"2099-01-12 00:00:00",
"status":0,
"created_at":null,
"updated_at":"2019-04-11 14:09:08"
},
{
"id":2,
"project_id":1,
"task_name":"fix task 1",
"task_description":"or something else",
"task_due":"2201-01-12 00:00:00",
"status":1,
"created_at":null,
"updated_at":"2019-04-11 14:10:11"
}
]
}]
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.id = id;
axios.get('/api/v1/projects/' + id)
.then(function (resp) {
app.project = resp.data;
})
.catch(function () {
alert("Could not load your projects")
});
},
data: function () {
return {
//client_id: null,
project: {
id: '',
clients_id: '',
products_id: '',
tasks_id: '',
project_name: '',
updated_at: '',
created_at: '',
clients: ''
},
task: {
status: ''
}
//client: []
}
},
methods: {
saveForm() {
var app = this;
var newproject = app.project;
axios.patch('/api/v1/projects/' + app.id, newproject)
.then(function (resp) {
app.$router.replace('/c/');
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
},
taskDone(taskid, projectid){
var app = this;
{{app}};
var newtask = app.task;
var flag = 1;
axios.patch('/api/v1/tasks/' + taskid + '?status='+flag)
.then(function (resp) {
app.$router.push('/pr/view/' + projectid);
location.reload();
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
},
taskUnDone(taskid, projectid){
var app = this;
{{app}};
var newtask = app.task;
var flag = 0;
axios.patch('/api/v1/tasks/' + taskid + '?status='+flag)
.then(function (resp) {
app.$router.push('/pr/view/' + projectid);
location.reload();
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
}
}
}
</script>

You could create a computed function that returns the length of tasks filtered by status of 1.
computed() {
status() {
const tasks = this.project.tasks;
const complete = tasks.filter(task => task.status === 1);
return `${complete.length}/${tasks.length}`;
}
}
Then use status as a "variable" in your markup.
<p>Tasks done: {{ status }}</p>

Related

Chrome DevTools Protocol - devtool can not get log info, when backend emit "Runtime.consoleAPICalled" event

I am writing a cdp backend for the chrome-devtool-frontend。
I can not see any output in chrome-devtool-frontend,when cdp backend emit "Runtime.consoleAPICalled" Event。
I make sure that I enable Runtime domain firstly.
"Runtime.executionContextCreated" event has been also emitted.
My cdp backend code:
const WebSocket = require('ws');
const executionContext = {
id: 1,
origin: 'http://my.local.xxxx.net:3000',
name: 'top',
};
(async () => {
const ws = new WebSocket(
'wss://xxxxxxxxx',
{ perMessageDeflate: false }
);
await new Promise((resolve) => ws.once('open', resolve));
console.log('connected!');
ws.on('message', (msg) => {
console.log(`Received: ${msg}`);
const messageObj = JSON.parse(msg);
const { id, method } = messageObj;
if (method === 'Log.enable' && id) {
ws.send(
JSON.stringify({
id,
result: {},
})
);
}
if (method === 'Debugger.enable' && id) {
ws.send(
JSON.stringify({
id,
result: {
debuggerId: '-252419454342719044.-5817058166285735043',
},
})
);
}
if (method === 'Runtime.runIfWaitingForDebugger' && id) {
ws.send(
JSON.stringify({
id,
result: {},
})
);
}
if (method === 'Runtime.enable' && id) {
ws.send(
JSON.stringify({
id,
result: {},
})
);
ws.send(
JSON.stringify({
method: 'Runtime.executionContextCreated',
params: {
context: executionContext,
},
})
);
setTimeout(() => {
ws.send(
JSON.stringify({
method: 'Runtime.consoleAPICalled',
params: {
type: 'log',
args: [
{
type: 'string',
value: 'log here',
},
],
stackTrace: { callFrames: [] },
executionContextId: 1,
timestamp: new Date().getTime(),
},
})
);
}, 3000);
}
});
})();
Here is devtool's Protocal monitor screenshot

Can't use $elemMatch"

When i am trying to hit the api for this part of code on postman i get error of Can't use $elemMatch I search but can't find any solution for that:-
const accessChat = asyncHandler(async (req, res) => {
const { userId } = req.body;
if (!userId) {
return res.status(400).json({err:'UserId param not sent with request'});
}
var isChat = await Chat.find({
isGroupChat: false,
$and: [
{ users: { $elemMatch: { $eq: req.user._id } } },
{ users: { $elemMatch: { $eq: userId } } },
],
})
.populate("users", "-password")
.populate("latestMessage");
isChat = await User.populate(isChat, {
path: "latestMessage.sender",
select: "name pic email",
});
if (isChat.length > 0) {
res.send(isChat[0]);
} else {
var chatData = {
chatName: "sender",
isGroupChat: false,
users: [req.user._id, userId],
};
try {
const createdChat = await Chat.create(chatData);
const FullChat = await Chat.findOne({ _id: createdChat._id }).populate(
"users",
"-password"
);
res.status(200).json(FullChat);
} catch (error) {
res.status(400);
throw new Error(error.message);
}
}
});
Error image is attached
https://i.stack.imgur.com/HXvTR.png

Function passing null at first run

i have a little problem with passing data into a JSON file. I have a function that runs onClick. The first run returned:
{
"title": "",
"description": "",
"price": "",
"id": 1
}
but all next runs returns data correctly:
{
"title": "Example title",
"description": "Example description",
"price": "$7",
"id": 2
}
Anyone know how to fix it?
My react code:
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const addToCart = (e) => {
e.preventDefault();
setTitle('Example title');
setDescription('Example description');
setPrice('$' + Math.floor(Math.random() * 10 + 1));
const product = { title, description, price};
fetch('http://localhost:8000/basket', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(product)
})
.catch((err) => {
console.log(err.message);
})
}
Because setState is async and only update when component re-render. So you can declare variable to use in post and in setState.
const addToCart = (e) => {
e.preventDefault();
const product = {
title: "Example title",
description: "Example description",
price: "$" + Math.floor(Math.random() * 10 + 1),
};
setTitle(product.title);
setDescription(product.description);
setPrice(product.price);
fetch("http://localhost:8000/basket", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(product),
}).catch((err) => {
console.log(err.message);
});
};
It's likely breaking because you're trying to set state while making a fetch call, on initial empty state values. The design here is wrong, you shouldn't be assigning hard coded state while making a fetch call.
const Form = () => {
const [value, setValue] = useState('')
const submit = () => {
// make fetch call here using value
}
return <form onSubmit={(e) => {e.preventDefault(); submit()}}>
<input type='text' value={value} onChange={(e) => setValue(e.target.value)}
</form>
}

Undefined binding(s) error in bookshelfJs to restrict returned columns

SERVICE
var Model = require('./../models');
var myService = function (query_params, callback) {
Model.User
.forge()
.fetch({
withRelated: [{
'org': function (qb) {
qb.column('id', 'name');
},
'role': function (qb) {
qb.column('id', 'role');
}
}]
})
.then(function (collection) {
return callback(null, collection);
})
.catch(function (err) {
return callback(err, null);
});
};
MODEL
var User = Bookshelf.Model.extend({
tableName: 'user',
org : function () {
return this.belongsTo(Org, 'org_id');
},
role : function () {
return this.belongsTo(Role, 'role_id');
}
});
var Users = Bookshelf.Collection.extend({
model: User
});
var Org = Bookshelf.Model.extend({
tableName: 'org',
user : function () {
return this.hasMany(User);
}
});
var Orgs = Bookshelf.Collection.extend({
model: Org
});
var Role = Bookshelf.Model.extend({
tableName: 'roles',
user: function() {
return this.hasMany(User);
}
});
module.exports = {
User: User,
Users: Users,
Org: Org,
Orgs: Orgs
};
The output I am getting the all fields of the user data, and specified field of respective user and role table,
How can I restrict the fields for user table.
I tried this:
.fetch({
withRelated: [{
'org': function (qb) {
qb.column('id', 'name');
},
'role': function (qb) {
qb.column('id', 'role');
}
}],
columns : ['id']
})
However, I am getting error :
Error: Undefined binding(s) detected when compiling SELECT query:
It was small error I was not passing the org_id and role_id in return column of parent with which binding will happen for children table.
.fetch({
withRelated: [{
'org': function (qb) {
qb.column('id', 'name');
},
'role': function (qb) {
qb.column('id', 'role');
}
}],
columns : ['id','org_id','role_id']
})

BackboneJS - this.collection is undefined

i have this Backbone View:
define(['backbone','handlebars', 'text!templates/AlphabetList.html'],
function(Backbone,Handlebars, Template) {
'use strict';
var View = Backbone.View.extend({
template: Handlebars.compile(Template),
events: {
'click li':'li_clickHandler'
},
li_clickHandler: function(e) {
var id = $(e.currentTarget).attr('data-id');
Backbone.history.navigate('/category/'+id, {trigger:true});
},
initialize: function () {
},
render: function() {
$(this.el).html(this.template({menu:this.collection.toJSON()}));
return this;
}
});
return View;
}
);
here is my router:
define([
'backbone',
//Views
'views/ArtistTopImage',
'views/AlphabetList',
'collections/AlphabetCollection',
],
function(
Backbone,
AlphabetList,
ArtistTopImage,
AlphabetCollection
) {
'use strict';
var ArtistRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
//Initializing the application
initialize: function () {
var self = this;
//Collections
this.AlphabetCollection = new AlphabetCollection({catId:0});
//Views
this.artistTopImageView = new ArtistTopImage({el:'.ti'});
this.AlphabetList = new AlphabetList({el:'#alphabetical', collection:this.AlphabetCollection});
self.artistTopImageView.render();
this.AlphabetCollection.fetch({success: function(collection) {
self.AlphabetList.collection=collection;
self.AlphabetList.render();
}});
Backbone.history.start({
pushState: false
});
},
//Default route.
index: function () {
var self = this;
},
});
return ArtistRouter;
}
);
And here is my Collection:
define([
"backbone",
"models/AlphabetModel"
],
function(Backbone, AlphabetModel) {
var AlphabetCollection = Backbone.Collection.extend({
model: AlphabetModel,
catId: null,
initialize: function(attrs) {
this.catId=attrs.catId;
},
url: function() {
return "Alphabetical"+this.catId+".json";
}
});
return AlphabetCollection;
});
The HTML template
<ol class="alist">
{{#each menu}}
<li data-id="{{this.url}}">{{this.name}}</li>
{{/each}}
</ol>
and the JSON file:
[
{
"name":"0-9",
"id":"1",
"url":"0"
},
{
"name":"A",
"id":"2",
"url":"1"
},
{
"name":"B",
"id":"3",
"url":"2"
},
{
"name":"C",
"id":"4",
"url":"3"
},
{
"name":"D",
"id":"5",
"url":"4"
}
]
this gives me an error: "this.collection is undefined". I dont know what the problem is, so does someone have an idea?