I have an object that looks like this:
visitorInfo: {
name: {
name: 'Name',
value: '',
isInvalid: false,
errors: []
},
email: {
name: 'Email address',
value: '',
validation: {
isRequired: true
},
errors: []
},
phone: {
name: 'Phone number',
value: '',
errors: []
}
},
I'm using watch to add error messages when the value of the fields changes (e.g. when the user is typing in a form):
fields: {
handler (fields) {
Object.entries(fields).forEach(([key, value]) => {
const field = fields[key]
const isRequired = field.validation.isRequired && field.value
if (isRequired) {
field.errors.push({
errorType: 'isRequired',
message: 'This field is required.'
})
}
})
},
deep: true
}
But as you can see there's a problem. This bit
field.errors.push({
errorType: 'isRequired',
message: 'This field is required.'
})
Will trigger an endless lop since it's modifying fields.
How to solve this issue?
Since vue cannot detect if you directly modify an array element, this might help:
field.errors[field.errors.length] = {
errorType: 'isRequired',
message: 'This field is required.'
};
Another option would be to simply check if the error has already been reported:
if (isRequired && !field.errors.length) { ... }
The downside of this is that it will still trigger the watcher an unnecessary 2nd time.
Let me know how it goes.
Related
I’m working on an application that sets a series of questions to generate an employee profile. As it is intended to be recursive, the user will be asked at the beginning and the end of the prompt to exit and terminate the enquire.
const employeeQuestions = [
// Role of employee
{
type: 'rawlist',
name: 'role',
message: 'What is the role of the employee?',
choices: [
'Engineer',
'Intern',
new inquirer.Separator(),
'Finish building the team', <=== THIS IS THE ANSWER THAT SHOULD TERMINATE THE PROMPT
],
default: 3,
},
// Employee questions
{
type: 'input',
name: `employee_name`,
message: answer => `Enter name of the ${answer.role}`,
},
{
type: 'number',
name: `employee_id`,
message: answer => `Enter ${answer.role} ID`,
validate(answer) {
const valid = !isNaN(parseFloat(answer));
return valid || 'Please enter a number';
},
filter: Number,
},
{
type: 'input',
name: `employee_email`,
message: answer => `Enter ${answer.role} Email address`,
},
// Engineer questions
{
when(answer) {
return answer.role === 'Engineer';
},
type: 'input',
name: `engineer_github`,
message: 'Enter GitHub username',
},
// Intern questions
{
when(answer) {
return answer.role === 'Intern';
},
type: 'input',
name: `intern_school`,
message: 'Enter intern school',
},
// add more employees
{
type: 'confirm',
name: `add_more`,
message: 'Do you want to add another employee?', <=== THIS IS THE QUESTION THAT SHOULD TERMINATE THE PROMPT
default: true,
},
];
// # Functions
// * Inquires all over if add_more = true
function inquireAgain() {
inquirer.prompt(employeeQuestions).then(answers => {
employeesInfo.push(answers);
if (answers.add_more) {
inquireAgain();
} else {
console.log(JSON.stringify(employeesInfo, null, ' '));
}
});
}
// * Initialize the inquirer prompts
async function init() {
const inquireManager = await inquirer.prompt(managerQuestions);
employeesInfo.push(inquireManager);
inquireAgain();
}
// # Initialisation
init();
this is the closest thing I found related to terminate the prompt, but is not working for me, Thanks in advance.
As the title states, my JS says an object is undefined even though if I console.log the parent it shows. I'm using prisma, but all that does is return a list of the objects containing {id, title, user:{id, name}}.
Code:
const userProjects = await prisma.projectMembers.findMany({
where: {
userId: token._id
},
select: {
project: {
select: {
id: true,
title: true,
user: {
select: {
id: true,
name: true,
},
},
},
},
},
});
userProjects.map(project => {
console.log(project)
console.log(project.user)
return {
id: project.id,
title: project.title,
user: project.user.id,
}
})
Output:
As you can see in the screenshot, there's a nested project property, and the user property is inside that. So project.user should be project.project.user.
userProjects.map(project => {
console.log(project)
console.log(project.project.user)
return project.project;
})
There's no need for you to create your own object when returning, since it's the same as project.project.
New to typescript, and I am working with nodeforge to generate CA and I do not know how to resolve this error.
PS: Vscode did not show red underline, but nextjs throws the error.
const cert = pki.createCertificate();
const attrs = [
{ name: 'commonName', value: 'My First CA' },
{ name: 'organizationUnitName', value: 'Organization Unit' },
{ name: 'organizationName', value: 'My Organization' },
] //this is returned by buildSubjectFromOptions
cert.setSubject(attrs as pki.CertificateField[]);
cert.setIssuer(attrs as pki.CertificateField[]);
At the last 2 lines, I am getting the error Attribute type is not specified, even though I followed vs code instructions as below
So I went to code of node-forge where the error was called, as follows
// populate missing type (OID)
if(typeof attr.type === 'undefined') {
if(attr.name && attr.name in pki.oids) {
attr.type = pki.oids[attr.name];
} else {
var error = new Error('Attribute type not specified.');
error.attribute = attr;
throw error;
}
}
Even though my attributes exists in pki.oids, i don't know why it still throws the error.
I amended my attributes format to as follows,adding the key type and now error goes away.
const attrs = [
{ name: 'commonName', value: 'My First CA', type: 'commonName' },
{ name: 'organizationUnitName', value: 'Organization Unit', type: 'organizationUnitName' },
{ name: 'organizationName', value: 'My Organization', type: 'organizationName' },
]
I have this schema for my user
const userSchema = mongoose.Schema({
firstName: {
type: String,
},
notifications : [{
description: String,
status: {
type: String,
enum : ['read', 'unread'],
default: 'unread'
},
dateAdded:{
type: Date,
default: Date.now
}
}],
})
supposedly I want to find the user _id first then insert a new object inside the new notification array. and it should look like this
{
_id: ObjectId('123')
firstName: 'John Doe'
notifications:[
{
description: 'somedescription'
status: 'unread'
},
{
description: 'somedescription2'
status: 'unread'
}
]
}
How can I achieve this, assuming that the notification property is non existent in the user document first, i need to check if notification property is present else add the notification property and push the new object
User.updateOne(
{ _id: userId },
{ $push: { notifications: {description: 'new notifications'} } }
)
this code is not working for me
Use $addToSet operator to achieve that
User.updateOne(
{ _id: userId },
{ $addToSet: { notifications: {description: 'new notifications'} } }
)
If that doesn't work try to add the default value too, and then that must work
User.updateOne(
{ _id: userId },
{ $addToSet: { notifications: {description: 'new notifications',
'status': 'unread'} } }
)
In my jsbin here http://jsbin.com/fecukitisu/edit?html,js,output. My total, and tax bindings are working until a user adds a new 'sale' via the included button. I cannot figure out why the computed functions return NAN when another sale is added. Any help is much appreciated!
It looks like an error with the return value of your component's data function. You have the "sale" property set to an array of objects. It should just be an object.
Change this:
data: function() {
return {
tip: 8.50,
sale: [
{ price: '' },
{ desc: '' },
{ amount: '' }
]
};
}
To this:
data: function() {
return {
tip: 8.50,
sale: {
price: '',
desc: '',
amount: ''
}
};
}