how to refactor this with ternary operator? - javascript

I might not need to refactor this code but now I'm just curious how to do it.
handleError: ({ error, email, password }, props) => authError => {
if (email === "" || password === "") {
return {
error: `Fields can't be empty`
};
} else {
return {
error: authError
};
}
}
this doesn't provide the same functionality as the code above:
handleError: ({ error, email, password }, props) => authError => {
email === "" || password === ""
? { error: `Fields can't be empty` }
: { error: authError };
}

You don't need any return. Since the only conditional logic is the message, it can be simplified as below.
handleError: ({ error, email, password }, props) => (authError) => ({
error: email === "" || password === "" ? `Fields can't be empty` : authError
})
Instead of return, you can wrap your object in parenthesis.

You just forgot the return
It should be:
handleError: ({ error, email, password }, props) => authError => {
return email === "" || password == ""
? { error: `Fields can't be empty` }
: { error: authError };
};

Something like this?
handleError: ({ error, email, password }, props) => authError => {
return email === "" || password === "" ? {error: "Fields can't be empty"} : {error: authError};
}

Related

Validator always return empty in graphql

the problem is, I am not able to make a request to MongoDB after validating the request with the following code:
module.exports.validateRegisterInput = (
username,
email,
password,
confirmPassword
) => {
const errors = {};
if (username.trim() === "") {
errors.username = "Username must be provided";
}
if (email.trim() === "") {
errors.email = "Email must be provided";
} else {
const validEmail =
/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
if (!email.match(validEmail)) {
errors.email = "Email must be valid";
}
}
if (password === "") {
errors.password = "Password must be provided";
}
if (password !== confirmPassword) {
errors.password = "Passwords must match";
}
return {
errors,
vaild: Object.keys(errors).length < 1,
};
};
the validators work fine and check the request for any mistakes but once there is no issue with the request it does not let me send a request and raises an error anyway, also I am using the validators in the following way:
module.exports = {
Mutation: {
async register(
parent,
{ registerInput: { username, email, password, confirmPassword } }
) {
const { valid, errors } = validateRegisterInput(
username,
email,
password,
confirmPassword
);
if (!valid) {
throw new UserInputError("Errors", { errors });
}
...
so, I solved the problem, the problem was I was not calling the question directly and changed it to:
validateRegisterInput(username, email, password, confirmPassword);
and add errors in the validators and not in the index
const { UserInputError } = require("apollo-server");
module.exports.validateRegisterInput = (
username,
email,
password,
confirmPassword
) => {
if (username.trim() === "") {
throw new UserInputError("Username must be provided", {
errors: {
username: "Username must be provided",
},
});
}
if (email.trim() === "") {
throw new UserInputError("Email must be provided", {
errors: {
email: "Email must be provided",
},
});
} else {
const validEmail =
/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
if (!email.match(validEmail)) {
throw new UserInputError("Email must be correct", {
errors: {
email: "Email must be correct",
},
});
}
}
if (password === "") {
throw new UserInputError("Password must be provided", {
errors: {
password: "Password must be provided",
},
});
}
if (password !== confirmPassword) {
throw new UserInputError("Passwords must match", {
errors: {
password: "Password must match",
},
});
}
};

updating array object in redux phrasing error?

I am trying to update an array object in react.js by accessing the index of the object.
I have written this code and am getting this error.
Parsing error: ',' expected.eslint
updateUserAvatar: (
state,
{ payload: { id, avatar } }: PayloadAction<UpdateUserAvatar>
) => {
const users = current(state.data.familyMembers)
const user = users.find((user) => user.id === id) as DashboardFamilyMember
const userIndex = users.findIndex((user) => user.id === id)
return {
...state,
data: {
...state.data,
familyMembers: [
...state.data.familyMembers,
//where error occurs
userIndex: {
...user,
avatar: avatar,
},
],
},
}
},
},
I know I can map through the array but I am confused as to why this doesn't work.
You can map over familyMembers array and update when you find user.id and update that avatar.
const users = current(state.data.familyMembers)
const familyMembers = users.map(user => {
if(user.id === id) {
return { ...user, avatar };
} else {
return user;
}
}
const userIndex = users.findIndex((user) => user.id === id)
return {
...state,
data: {
...state.data,
familyMembers: familyMembers,
},
};

Сan’t create a user in the Firebase Database

Сan’t create a user in the Firebase Database pls help or
tell me a documentation on this question.
Is it right stroke user_id: cred.user.uid ?
methods: {
signup(){
if(this.alias && this.email && this.password){
this.feedback = null
this.slug = slugify(this.alias, {
replacement: '-',
remove: /[$*_+~.()'"!\-:#]/g,
lower: true
})
let ref = db.collection('users').doc(this.slug)
ref.get().then(doc => {
if(doc.exists){
this.feedback = 'This alias already exists'
} else {
// this alias does not yet exists in the db
firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
.then(cred => {
ref.set({
alias: this.alias,
geolocation: null,
user_id: cred.user.uid
})
}).then(() => {
this.$router.push({ name: 'GMap' })
})
.catch(err => {
this.feedback = err.message
})
}
})
} else {
this.feedback = 'Please fill in all fields'
}
}
}
See the solution in the comments below
https://www.udemy.com/course/build-web-apps-with-vuejs-firebase/learn/lecture/10015192#questions/11358100

express validator - custom password validator cannot read property of undefined

I have a simple validator that checks if "password" = "passwordconf"
exports.RegisterUser = [
check('username').isLength({ min: 1 , max: 10}).trim().withMessage("Length 1-10"),
check('password').isLength({ min: 6 , max: 10}).trim().withMessage("Length 6-10"),
check('passwordconf').isLength({ min: 6 , max: 10}).trim().withMessage("Length 6-10"),
check('passwordconf').custom((value , { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation is incorrect');
}
}),
sanitizeBody('*').trim().escape(),
function ( req , res ) {
//check for errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
var user = new User({
username : req.body.username,
password : req.body.password
});
var username = req.body.username;
//check if user is in DB
User.findOne({ 'username' : username})
.exec(( err , docs) => {
if (err) {
res.send('There was an error');
return err;
} else if (!docs) {
//username does not exist
user.save((err) => {
if (err) {
return next(err)
} else {
//saved it
res.send('saved a new user!')
}
})
} else {
res.send('Username exists!')
}
})}
}]
if i comment out this statement,
check('passwordconf').custom((value , { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation is incorrect');
}
})
the code works.I copied this statement from the official docs https://express-validator.github.io/docs/custom-validators-sanitizers.html
I gives me this error when saving a new user
{"errors":[{"location":"body","param":"passwordconf","value":"password1","msg":"Cannot read property 'then' of undefined"}]}
What is missing here?
This is a known bug, and will be fixed in the next release (current one being v5.2.0).
Custom validators that return nothing fail with that error.
To work around this, you can simply return true from your validator:
check('passwordconf').custom((value , { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation is incorrect');
}
return true;
})

Firebase user displayName is null

I'm running this code in my react app:
componentDidMount() {
modelInstance.addObserver(this);
modelInstance.getSignInStatus().then((user)=>{
this.setState({
userName: user !== false ? user.displayName : "Sign in",
logged_in: user !== false ? true : false
});
});
}
And here is modelInstance.getSignInStatus():
this.getSignInStatus = function () {
return new Promise((resolve, reject)=>{
firebase.auth().onAuthStateChanged(function(user){
if (user){
resolve(user);
}
else {
resolve(false);
}
});
});
}
What happens is that this.state.userName is set to null, meaning that user.displayName is null. Why is this?
state = {
username: "",
email: "",
passwordOne: "",
passwordTwo: "",
error: null
};
onSubmit = event => {
const {username, email, passwordOne} = this.state;
const {history} = this.props;
auth
.createUserWithEmailAndPassword(email, password);
.then(authUser => {
db.doCreateUser(authUser.uid, username, email).then(() => {
//you should clear your state fields here, for username / email etc
console.log(authUser);
//redirect user
history.push(routes.HOME);
});
})
.catch(error => {
this.setState({error});
});
event.preventDefault();
};
const auth = firebase.auth();
const db = firebase.database();
in order to acess doCreateUser
const doCreateUser = (id, username, email) =>
db.ref(`users/${id}`).set({
uid:id,
username,
email,
});
I would use setState for checking the auth status like so:
firebase.auth().onAuthStateChanged(function(user){
if (user){
this.setState({user});
}
}
Then you want the state of the displayName of the current user
componentDidMount() {
modelInstance.addObserver(this);
modelInstance.getSignInStatus().then((user)=>{
this.setState({
userName: this.state.user ? this.state.user.displayName : "Sign in",
logged_in: this.state.user ? true : false
});
});
}
Obviously there has to be a name in the displayName property, If not you would have to update it. Let me know how this turns out.

Categories