I am using formik (https://github.com/jaredpalmer/formik) for forms of my react application.
I want to be able to update component state to show a success message after handleSubmit completed successfully.
But I am unable to achieve that. I am getting errors.
export default withFormik({
mapPropsToValues ({ email }) {
return {
email: email || ''
};
},
validationSchema: Yup.object().shape({
email: Yup.string().email('Email not valid').required('Email is required')
}),
handleSubmit(values, { resetForm, setErrors, setSubmitting }) {
Accounts.forgotPassword({
email: values.email
}, (error) => {
if (error) {
setErrors({ email: 'Error: ' + error.reason });
} else {
this.setState({success: 'Success: Check your inbox for a reset link!'});
resetForm();
}
setSubmitting(false);
});
}
})(RecoverPassword);
We can't access to wrapped component from a higher order component.
There is no way to access a wrapped component's state from a higher-order component. Formik has a built-in errors and status handling setters and getters.
export default withFormik({
mapPropsToValues ({ email }) {
return {
email: email || ''
};
},
validationSchema: Yup.object().shape({
email: Yup.string().email('Email not valid').required('Email is required')
}),
handleSubmit(values, { resetForm, setErrors, setSubmitting, setStatus }) {
Accounts.forgotPassword({
email: values.email
}, (error) => {
if (error) {
setErrors({ email: 'Error: ' + error.reason });
} else {
resetForm();
setStatus('Check your inbox for a reset link.');
// setStatus is part of the "formik bag".
}
setSubmitting(false);
});
}
})(RecoverPassword);
Related
I am doing a POST to an enpoint to authenticate users. The endopoint is "/user/login". I make a post and receive status code 200 but the Postman, and also my client, are waiting for the RES object that does not arrive.
This is a screenshot of the API call through Postman:
This is controler in server side:
router.post(
'/user/login',
passport.authenticate('local'),
UserCtrl.getLogin,
)
getLogin = (req, res, next) => {
console.log("req: ", req.body)
console.log('logged in', req.user);
var userInfo = {
username: req.user.username
};
res.json(userInfo)
}
The console prints the lines in the controller, and the user is effectively authenticated, for example:
req: { username: 'fedex', password: 'fedex' }
logged in {
_id: new ObjectId("62a8b00f468c563699d7dfc2"),
username: 'fedex',
password: '$2a$10$cdbh0oCBNpHxxwebsvArLOAFwetVAh5LTnQwk1Lg9kjWkjAWhfxym',
__v: 0
}
probably the problem is in the invocation of the local passport strategy, but I only do the standard:
const strategy = new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err)
}
if (!user) {
return done(null, false, { message: 'Incorrect username' })
}
if (!user.checkPassword(password)) {
return done(null, false, { message: 'Incorrect password' })
}
return done(null, user)
})
}
)
EDITED: If I remove the middleware where the passport.authenticate('local') is invoked, and incorporate the authentication functionality directly in the controller, it works. But what is wrong with calling passport in the route?
BEFORE (does not work):
router.post(
'/user/login',
passport.authenticate('local'),
UserCtrl.getLogin
)
AFTER (adding passport authentication inside the controller, it work)
router.post(
'/user/login',
UserCtrl.getLogin
)
I'm trying to delete a todo while using thunkApi.fulfillwithValue and thunkApi.rejectWithValue but I cant seem to get the types right.
import { createAsyncThunk } from '#reduxjs/toolkit';
interface DeleteTodoError {
message: string;
}
interface DeleteTodoSuccess {
message: string;
}
export const deleteTodos = createAsyncThunk<DeleteTodoError | DeleteTodoSuccess, number>(
'todos/delete',
async (todoId: number, thunkApi) => {
try {
const response = await fetch(`${process.env.baseUrl}/todos/${todoId}`, {
method: 'delete',
});
if (response.status === 200) {
return thunkApi.fulfillWithValue({
message: 'todo deleted successfully',
});
}
} catch (error) {
return thunkApi.rejectWithValue({
message: 'failed to delete todo',
});
}
}
);
The rejected type is defined in the third generic argument.
You can find the docs on that here
export const deleteTodos = createAsyncThunk<
DeleteTodoSuccess,
number,
{
rejectValue: DeleteTodoError
}
>(
I want to display an additional input if the person clicks yes and clicks on nothing
i try to do that with v-if but i the value never change
this is the entire page in vuejs maybe i need to do a method, i already try without quote and with, i to set value like club = 1 but didn't work to.
I'm not sure if my v-bind is good too
<el-form-item label="Possédez vous un club ?">
<el-radio-group v-model="ruleForm.club">
<el-radio label="Oui" v-bind:value="true"></el-radio>
<el-radio label="Non" v-bind:value="false"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item v-if="'ruleForm.club' == true" label="Nom du club" prop="nClub">
<el-input v-model="ruleForm.nClub" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" #click="submitForm('ruleForm')">Submit</el-button>
<el-button #click="resetForm('ruleForm')">Reset</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data () {
var validatePseudo = (rule, value, callback) => {
if (value === '' || value !== 'coach') {
callback(new Error('Please input the pseudo'))
} else {
callback()
}
}
var validatePass = (rule, value, callback) => {
if (value === '' || value !== 'password') {
callback(new Error('Please input the password'))
} else {
callback()
}
}
return {
ruleForm: {
nom: '',
prenom: '',
pseudo: '',
email: '',
pass: '',
statue: '',
club: '',
nClub: ''
},
rules: {
pseudo: [
{ validator: validatePseudo, trigger: 'blur' }
],
pass: [
{ validator: validatePass, trigger: 'blur' }
]
}
}
},
methods: {
submitForm (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$router.push({
name: '/'
})
} else {
console.log('error submit!!')
return false
}
})
},
resetForm (formName) {
this.$refs[formName].resetFields()
},
}
}
</script>
I do not really understand your question, but from what I can tell you would like to add an inputfield if a user selects a certain radio button using v-if. I've recreated this in a jsfiddle. Is this wat your looking for?
Link: https://jsfiddle.net/Mertakus/8wx4h7up/3/
Ok, I've got the following in one of my controllers:
User.find({email: 'email#example.com'}).then(function (user) {
user[0].field = 'new_value';
user[0].field_2 = 'new_value';
console.log(user[0], 'before saving');
user[0].save();
console.log(user[0], 'after saving');
});
If I console user[0] at this stage I can see the updated fields. However the changes were not saved to the db. If I do the following:
User.find({email: 'email#example.com'}).then(function (user) {
user[0].field = 'new_value';
user[0].field_2 = 'new_value';
user[0].save();
User.find(user[0].id).then(function (updateduser) {
console.log(updateduser[0])
});
});
The updateduser does not have the updated fields... Why is that? How can should I proceed in this case?
Actually
user[0].save();
will return a promise like you have done for User.find().then();
user[0].save() is an asynchronous call so the next call to find the user will run even though the user[0] is not updated in the database.
so place the second find command inside the then of save() function and you will get the updated user.
user[0].save().then(function(err){
User.find(user[0].id).then(function (updateduser) {
console.log(updateduser[0])
});
}))
Why you not use updated() method?
User.find({ email: 'email#example.com' })
.then(function(user) {
if (!user) return res.notFound();
User.update({ eamil: 'eamil#example.com' }, {
field: 'new_value',
field_2: 'new_value'
})
.then(function(updated_user) {
console.log(updated_user);
return res.ok();
})
.catch(function(err) {
sails.log.error(err);
return res.serverError();
});
})
.catch(function(err) {
sails.log.error(err);
return res.serverError();
});
First of all, you want to update only one user data because you are using user[0](I think).
So it is easy to use findOne().
Simple code
User
.findOne({email: 'email#example.com'})
.exec(function(err,user){
if(err || !user) {
//handle here
}
else {
user.key1 = 'new_value';
user.key2 = 'new_value';
user.save(function(err){
if(err){
//handle error
}
console.log('updatedUser',user)
})
}
})
Thank you.
I use the following piece of code to create some records. If I provide incorrect values, say(password and passwordConfirmation does not match), then sometimes an institute record is created without a rollback and sometimes, rollback happens properly.
I would appreciate any help. Is there a better way to do this?
create: function (req, res) {
User.query("BEGIN TRANSACTION", function(result){
if(result) {
sails.log.info(result);
return res.serverError(result);
} else {
Institute.create({
name: req.param('name'),
shortName: req.param('shortName'),
phoneNumber: req.param('phoneNumber'),
subdomain: req.param('subdomain'),
managerEmail: req.param('email')
}, function(error, institute){
if(error) {
sails.log.info(error);
Institute.query("ROLLBACK", function(result) {
sails.log.info(result);
return res.badRequest(error);
});
} else {
User.create({
email: req.param('email'),
password: req.param('password'),
passwordConfirmation: req.param('passwordConfirmation'),
account: institute.id
}, function(error, user) {
if(error) {
sails.log.info(error);
Institute.query("ROLLBACK", function(result) {
sails.log.info(result);
return res.badRequest(error);
});
} else {
User.query("COMMIT", function(result){
sails.log.info(result);
return res.created(user);
});
}
});
}
});
}
});
}
You have a few of options, in no particular order.
1. Write a function that makes all the possible security checks before creation occurs, or use the beforeCreate life cycle call for your models.
For example, you could write a function verifyParams(params) that makes checks such as password comparison (and any other checks you want) for your user creation parameters before you create the institution, or you could just include these checks in your institution creation's beforeCreate method.
2. Delete if there is an error during your user creation
Delete theInstitute model instance in your error case of user creation:
...
User.create(..., function (error, user) {
if (error) {
Institute.destroy(institute.id, function instDestroyed(err) {
...
});
} else {
...
}
});
3. Create a user in your institute model's beforeCreate method.
module.exports = {
attributes: { ... },
beforeCreate: function(values, next) {
User.create(..., function (err, user) {
if (err) { return next(err) }
return next();
});
}
}
Personally, I use method #2 in my own apps.