react hook form - after first error cannot validate again - reactjs

Good Day!
Today i am faced with a problem regarding react hook form.
I am setting a custom error using setError in case there is an error when loggin in.
The problem:
After the first error, I cannot validate the form again.
ex)
login fail with either wrong id or password => received error message from the backened.
error is set using setError
re-write the form and trying to submit again => cannot send login api to the backened.
Anyone had similar issues like myself?
const onValid = async (data) => {
const res = await SignIn(data);
if (res.data.result) {
const result = setSessionKey(res.data.loginInfo.sessionKey);
console.log(result);
clearErrors();
} else {
return setError('loginFail', { message: 'login failed' });
}
};

Related

How to handle 401 error using useQuery in Typescript

I came across the following code to handle 401 error
const { useQuery } = require("react-query");
const useAuthedQuery = (...options) => {
const query = useQuery(...options);
if (query?.error?.response?.status === 401) {
// Insert custom access-token refresh logic here. For now, we are
// just refreshing the page here, so as to redirect them to the
// login page since their token is now expired.
window.location.reload();
}
return query;
}
export default useAuthedQuery;
Could anyone help me about with how to use the same with Typescript thanks

Exposing error messages from Auth.forgotPassword and other Auth methods

Is there a way to see all available error messages that are returned from the #aws-amplify/auth Auth methods?
When calling Auth.forgotPassword with the correct username, I receive the verification code to reset my password. However, when I put an invalid username, there is no error. Am I doing something incorrect here? I receive the LimiteRateExceeded error when trying too many times but nothing else.
Its worth noting that I am not using the default amplify react ui and am using my own form that calls the onSubmit.
Here is my onSubmit function that calls Auth.forgotPassword
const onSubmitStep1 = async (formData: any) => {
console.log('formData1', formData)
setSubmitting(true)
await Auth.forgotPassword(formData.email)
.then(() => {
setSubmitting(false)
stepForward()
})
.catch((err) => {
console.log(err.message)
setAmplifyErrors({
...amplifyErrors,
form1: err.message,
})
})
}

Resetting multiple react Context API states at ones instead of creating resting action for each of them?

I have about 5 separate context api states that I want to rest after logging out from app, since they casing lots of issues any idea how to rest them redirecting doesn't seem to be doing much, and I don't want to refresh, this issue is my log out function will logout the user from server and simply redirect to main page but the state is still in the memory ?
const SignOut = () => {
signOut(auth)
.then(() => {
// Sign-out successful.
})
.catch((error) => {
// An error happened.
const errorCode = error.code;
const errorMessage = error.message;
snackbar.Msg(error, 'A signout error has happened.');
});
history.push('/');
};

React login using context API with private route

In my react web app, login-logout functionality is implemented using context-API and hooks. Everything seems to work fine except for the fact that I have to click the 'Login' button twice to push the user to the dashboard.
The statement, return <Redirect to="/dashboard /> does not work, instead I have to use history.push('/dashboard'), which does not seems to be a better option to me while login.
Here is the working snippet :
https://codesandbox.io/s/wizardly-worker-mqkex?file=/src/AuthContext.js
Also, I need some suggestions for the best practise to fetch the logged user details in other components. Using localstorage or global context API state, which of them serves as the best option for the same ?
Any help to resolve this, appreciated :)
Well, it boils down to the simple fact that your context is not updated when you do your check. The simplest solution would be to remove the check for isLoggedIn and push the user to the Dashboard:
const postLogin = async (e) => {
e.preventDefault()
try {
await login()
props.history.push('/dashboard')
} catch (error) {
dispatch({
type: 'LOGIN_FAILURE',
payload: 'Unable to login'
})
}
}
Then throw an error in your login function when you don't get a 200 back:
const login = async () => {
const loginUser = { status: 200, id: '3654634565659abhdgh' }
if (loginUser.status === 200) {
dispatch({
type: 'LOGIN_SUCCESS',
payload: loginUser.id
})
} else {
throw new Error("Invalid Credentials")
}
}
As your login code is in a try catch block, the user won't get pushed to the Dashboard when the login fails.

Navigation failed after logging in with react-native-fbsdk

I am using the FBSDK to do the registration in react native. I need the name, last name and email in order to pass it to the registration screen and fill the mentioned fields there automatically. Here is my code in login screen:
async _fbAuth() {
//console.log("that", that);
let { isCancelled } = await LoginManager.logInWithReadPermissions(['public_profile','user_posts', 'email','user_birthday']);
if ( !isCancelled ) {
let data = await AccessToken.getCurrentAccessToken();
let token = data.accessToken.toString();
// await afterLoginComplete(token);
const response = await fetch(
`https://graph.facebook.com/me?fields=id,email,name,first_name,last_name,gender,picture,cover&access_token=${token}`);
let result = await response.json();
this.setState({result});
console.log('result result result ', result);
//navigate to complete the registration.
this.props.navigation.navigate('Reg_1', {name: this.state.result.name, email: this.state.result.email, surname: this.state.result.last_name })
}
else {
console.log('Login incomplete');
}
}
Also I have this button to call the function:
<ButtonFB
onPress={ this._fbAuth}
isLoading={false}
isEnabled={true}
label={I18n.t("Accedi_con_Facebook")}
style={commonStyle.Button}
/>
Everything works fine and the data retrieved well. The only problem is the part of navigation and setSate. My problem is that the 'this' has been lost during the login with the facebook. I got the following warning after doing the login with facebook.
Possible: Unhandled promise rejection (id:0): type error:
this.setState is not a function
I also tried to bind the function of _fbAuth, but it doesn't work. Can you help me to solve this problem. Thanks in advance.
You need to bind the function as
_fbAuth = async () => {}
Since this is not being referenced in _fbAuth function.
For more info checkout this artice

Categories

Resources