Transforming observer object in VueJS - javascript

I'm trying to validate the form and usually i do it the way i'm going to put here, problem is that I can't assign object to component object, also it doesn't show it in template if component data changes, should i use watch and how to do it since i learn Vue:
validate(data) {
Object.entries(data).map(field => {
if (field[1] == "") {
errors[field[0]] = "Can't be blank";
} else if ( data.password !== "" &&
field[0] == "confirm_password" &&
field[1] !== data.password {
errors[field[0]] = "Passwords don't match";
}
});
return errors;
},
signUp(data) {
this.errors = JSON.parse(JSON.stringify(this.validate(data)));
console.log(this.errors);
if (Object.keys(this.errors).length == 0) {
this.register(data);
}
}
'data' is object inside the data of the component...
I tried to transform it this way JSON.parse((JSON.stringify(object)), tried also Object.assign({}, this.validate(data)), {...this.validate(data)}

Related

JS is or is not if else

How could I simplify this action below.
I realize this is ridiculous.
But everything I'm trying to do, either one works and one doesn't and vice versa.
I need to send data if this field is not empty. if it is empty, then don't send it: admin|power
it's either null or not
const mreq = await Model.findOne({
where: {
id: req.params.id,
old: req.params.times
}
})
if (!mreq) {
return
} else if (mreq.admin == null) {
return
} else if (mreq.admin) {
res.json(mreq.admin)
} else if (mreq.power == null) {
return
} else if (mreq.power) {
res.json(mreq.power)
}
You don't need all the branches that don't return anything - just test for the two values to be .jsond in two ifs. Use optional chaining to keep things concise.
const mreq = await Model.findOne({ where: { id: req.params.id, old: req.params.times } })
if (mreq?.admin) {
res.json(mreq.admin)
} else if (mreq?.power) {
res.json(mreq.power)
}
Considering that perhaps the property "admin" can be boolean (I don't konw)
You can do something like this:
if(mreq && mreq.admin !== null) {
res.json(mreq.admin);
return;
}
if (mreq.power) { res.json(mreq.power) }
I hope you find it useful.

How to get default value of dropdown input in reactjs

I am trying to get the default value of dropdown input field as I am using it for both add and update. Below is my code
<BrInput
type="select"
name="altPayableInd"
id="altPayableInd"
options={altPayableIndOpt}
default={payableResp.payable[index] && payableResp.payable[index].altPayableInd.value && this.setDefaultValue(payableResp.payable[index] && payableResp.payable[index].altPayableInd.value, altPayableIndOpt)}
/>
setDefaultValue = (value, options) => {
let matchedLabel = options.find(el => el.value === value);
if (value !== "O") {
this.setState({ viewReason: false })
}
return [{ value, label: matchedLabel.label }]
}
error :
Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
Ideally, you should use only get methods when you are setting prop values in render.
In setDefaultValue you are using setState, which becomes invalid, thats what your error says. You have to move this to some another logic.
To make this work as it is, use as this: (code is commented here, just to show error part, you can remove this)
setDefaultValue = (value, options) => {
let matchedLabel = options.find(el => el.value === value);
// if (value !== "O") {
// this.setState({ viewReason: false }) // you can't use setState in render
// }
return [{ value, label: matchedLabel.label }]
}

How can I optimize my validation code in reactjs?

Below, I have mentioned my JS code. So, Kindly suggest or guide me that there is any better approach to implement the validation on form submit for react project or is it right approach which i have implemented already?
submitUserForm = (e) => {
e.preventDefault();
const { formError } = this.state;
let valid = true;
if(document.getElementById('useremail').value === "") {
valid = false;
formError.email = "Kindly enter your email id"
}
else {
valid = true;
formError.email = ""
}
if(document.getElementById('userpassword').value === "") {
valid = false;
formError.password = "Kindly enter the password"
}
else {
valid = true;
formError.password = ""
}
if(valid === true) {
this.formSubmitApi();
}
this.setState({
isValid: valid,
formError
})
}
This is how you can improve your code:
submitUserForm = (e) => {
e.preventDefault();
const formError = {}
if(document.getElementById('useremail').value === "") {
formError.email = "Kindly enter your email id"
}
if(document.getElementById('userpassword').value === "") {
formError.password = "Kindly enter the password"
}
Object.keys(formError).length === 0 && this.formSubmitApi();
this.setState({
formError
})
}
First of all, in order to improve your code, you need to have controlled components (Inputs in this case) in order to store your values in the state and then use them in the submitUserForm function, also, instead of valid variable, I'll use a validation function like (Also, make the useremail and userpassword objects, in order to store the errors there):
state = {
useremail: { value: '', error: '' },
userpassword: { value: '', error: '' },
};
validateValue = value => {
return value !== undefined && value !== null && value !== '';
};
submitUserForm = e => {
const { useremail, userpassword } = this.state;
e.preventDefault();
// If both the 'useremail' and the 'userpassword' pass the 'validateValue' validations, then send the data
if (this.validateValue(useremail.value) && this.validateValue(userpassword.value)) {
this.formSubmitApi(useremail.value, userpassword.value);
// After sending the info, we reset our two states to initial state
this.setState({useremail: { value: '', error: '' }, userpassword: { value: '', error: '' } });
} else {
// If 'useremail' don't pass the validation we store the error
if (!this.validateValue(useremail.value)) {
this.setState({ useremail: { value: useremail.value, error: 'Please enter a valid email' }});
}
// If 'userpassword' don't pass the validation we store the error
if (!this.validateValue(userpassword.value)) {
this.setState({ userpassword: { value: userpassword.value, error: 'Please enter a valid password' }});
}
}
};
I think this is a more clean approach, you only have to states instead of three as before and you can get all the information that you need from those states.
I would change 2 things:
Make the inputs controlled, so that you have better and direct control of the input. Accessing the inputs with document.getElementById is bad practice. Save the text of each input within the state or use refs.
I would change the check for valid input into something like this:
const errors = {};
errors.email = "Kindly enter your email id"
if (Object.keys(errors).length === 0) {...}
It should be a new object, so that you don't mutate the state and this makes it easier because you don't have a second variable.
I hope this helps. Happy coding.

Null checking object not working

i'm trying to check for null value , even when i know the values are null the loop still doesn't break. Cheers for any help
constructor(){
super();
this.state = {
warningMsg: 'No Warnings'
}
this.detail = {
name: null,
phone: null,
email: null,
location: null,
extraDetail: 'Default'
}
}
handleSubmit(){
const {DetailStore} = this.props;
for (let value in this.detail) {
console.log(value)
if (value === null) {
console.log('null found'); // i should see this in console but i don't
this.setState({warningMsg:'Check Input'});
break;
}
}
DetailStore.entDetail(this.detail);
console.log(DetailStore.getDetail,'Submitted');
}
The 'value' in your for loop is actually the property name. You need to check:
if (this.detail[value] === null)
What you actually want is:
const detailValues = Object.values(this.detail);
for (const value of detailValues) {
console.log(value)
if (value === null) {
console.log('null found'); // i should see this in console but i don't
this.setState({
warningMsg: 'Check Input'
});
break;
}
}
for..in loops iterate over the property names of the object, not the value of the property. If you want to iterate over object values, better to use Object.values instead:
if (Object.values(this.detail).some(value => value === null)) {
console.log('null found');
this.setState({warningMsg:'Check Input'});
}

Acess node firebase and check value

I would like to access the node "status" and check: if false writes data, if true returns error alert.
I used the code:
var reference_value_of_counter = firebase.database().ref('contador/valor');
var reference_to_increment_counter = firebase.database().ref('contador/valor');
var reference_status_attendance = firebase.database().ref('agendamentos/primeiro-horario/status');
var reference_to_data_register = firebase.database().ref('agendamentos/primeiro-horario/');
if (reference_status_attendance.once('value', snap => snap.val() == false)) {
reference_value_of_counter.once('value', snap => reference_to_increment_counter.set(snap.val()+1));
reference_to_data_register.update({nome : 'isaac', sobrenome : "menezes", status: true});
}
else {
alert("sorry");
}
if (reference_status_attendance.once('value', snap => snap.val() == false))
This statement is not correct. once function wouldn't return the value that you return from your callback. You need to access the value and perform the if/else inside the callback. I haven't tested the below code but it should work or at least give you an idea of what needs to be done.
reference_status_attendance.once('value', snap => {
if(snap.val() == false) {
reference_value_of_counter.once('value', snap => reference_to_increment_counter.set(snap.val()+1));
reference_to_data_register.update({nome : 'isaac', sobrenome : "menezes", status: true});
}
else {
alert("sorry");
}
})
See Firebase Documentation
var reference_to_data_register = firebase.database().ref('agendamentos/primeiro-horario/');
reference_to_data_register.once('value')
.then(function(dataSnapshot) {
if(dataSnapshot.val().status){
//do this if status is true
} else {
// do this is status is false
}
});

Categories

Resources