After Login I want to show a license agreement page.
To show the license I used this code
index.js
componentWillMount(){
this.props.actions.user.LicenseAgreement();
}
action.js
export const LicenseAgreement = () => {
return(dispatch) =>{
authService.LicenseAgreement()
.then((response) =>{
window.location.href="/";
dispatch({type: LICENSE_AGREE, payload:response});
})
.catch((error)=>{
notification.error({
message: 'User',
description: error.message,
})
})
}
}
reducer.js
case LICENSE_AGREE: {
return{...state, agreement: action.payload.data.text}
}
The problem is that the page refreshes before clicking Agree button .
But when I commented componentWillMount() there was no refreshing.
So how could I stop refreshing of this page?
Use componentDidMount life cycle and remove window.location.href. Also to avoid refreshing, you can user Router
Related
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.
I'm creating a blog, using React.
I uploaded some parts: https://codesandbox.io/s/youthful-bush-z3cce
There is one note on the main page and a list of other notes. When I click on some link of these notes, it opens and I can see another post. But if I try to click again on another post, it doesn't reload, though it changes the url.
It's because you have the same component rendering your posts. Your componentDidMount runs only once and it is responsible for calling your api. You need to get the api logic in a different function and call it again in componentDidUpdate.
I have done it in a codesanbox repo - https://codesandbox.io/s/musing-grass-sxokl
componentDidMount() {
if (!this.props.match) {
return;
} else {
this.callApi();
}
}
componentDidUpdate() {
this.callApi();
}
callApi = () => {
client
.getEntries({
content_type: "blogPost",
"fields.slug": this.props.match.params.slug
})
.then(response => {
console.log(response);
this.setState(
{
content: response.items[0].fields.content,
title: response.items[0].fields.title,
date: response.items[0].fields.date,
country: response.items[0].fields.country
},
() => console.log(this.state)
);
});
};
Hope this helps you.
I am currently working on pushing to a log in page on the confirmation of a user via email. Problem is, I would like to first re-direct the user confirming to a page thanking them for registering and a few seconds later push to the log in page. What's the best way of approaching this?
I have a push to the log in page that is happening right away, would like to delay it a few seconds.
confirmSuccess = () => {
this.setState(() => ({ success: true }));
this.props.history.push("/login", { fromRegistration: true });
};
Currently as soon as the user clicks on "confirm account" it pushes them straight the log in page, would like to have it delayed so the "thank you for registering" page can appear first.
You can create a new component like this
import React from "react"
import { withRouter } from "react-router-dom"
class ThankYouComponent extends React.Component {
componentDidMount() {
setTimeout(() => {this.props.history.push("/login")}, 5000) // redirect in 5 secs
}
render() {
return(
<h1>Thank You</h1>
)
}
}
export default withRouter(ThankYouComponent)
and in your confirmSuccess function redirect to ThankYouComponent page instead:
confirmSuccess = () => {
this.setState(() => ({ success: true }));
this.props.history.push("/thankYouPage", { fromRegistration: true });
};
And of course don't forget to add ThankYouComponent to Routes
Summary:
I am using firebase for authentication. I am trying to singout using the firebase signout() method. After signout user is navigating to the login scene using Actions.auth(). [auth is my login form scene name]
Issue:,
After using sign out it properly navigates to the login screen.
But when I login again it shows me blank screen. And when I do any activity e.g. touch the screen in the blank space then the data appears again.
I think I am doing something wrong [obviously haha] or I am missing some fundamentals.
Looking for help.
All I need user to logout and navigate to the login screen.
1. I created action in types.js
export const LOG_OUT_USER = 'log_out_user';
2. I created an action in AuthActions.js and imported on top 'LOG_OUT_USER' and added the code as below
export const logOutUser = () => dispatch => {
firebase.auth()
.signOut()
.then(() => {
console.log('Sign-out successful');
dispatch({ type: LOG_OUT_USER });
Actions.auth();
})
.catch(error => {
console.log(error);
});
};
3. in AuthReducer.js I imported the 'LOG_OUT_USER' and added the case as below
const INITIAL_STATE = {
email: '',
password: '',
user: null,
error: '',
loading: false
};
case LOG_OUT_USER:
return INITIAL_STATE;
4. I added a logout button in Employee List.
//imported the action
import { employeesFetch, logOutUser } from '../actions';
//added function after 'componentWillReceiveProps' function
onButtonPressLogout() {
console.log('logout');
this.props.logOutUser();
}
//added card section with logout button
<CardSection>
<Button onPress={this.onButtonPressLogout.bind(this)}>
Log Out
</Button>
</CardSection>
//exported at the bottom
export default connect(mapStateToProps, { employeesFetch, logOutUser })(EmployeeList);
In case you want to look at repo: https://github.com/hemantc09/react-native-Manager-Employee-App
Just download and run command : - react-native run-ios
Ouput:
First time login:
After logout and then re-login: shows . blank screen.
I see in the console the user data is still printing even after logout.
What I a missing here.
If you want to take look using testflight let me know. I will send you invite.
I have got the url to change to the url I want it to, but the only way I can get it to work is by refreshing the page and then it goes to the url.
An example is lets say I am on localhost:3000/signin and when I sign in I want the user to be redirected to the posts page on localhost:3000/posts. When I click the button I get localhost:3000/posts but the page just stays on the signin page. I have to hit refresh for it to go to that URL.
**********
EDIT: I also noticed that when I hit back or forward in the browser that it isn't rendering till I hit refresh also. So this could be some other issue? I am using react-router-v4.
Here is the code I have so far:
This is the on submit function being called when the button is clicked:
onSubmit({email, password}) {
this.props.signinUser({email, password}, () => {
this.props.history.push('/posts');
});
}
this is the action signinUser:
export function signinUser({email, password}, cb) {
return function(dispatch) {
axios.post(`${ROOT_URL}/signin`, {email, password})
.then((response) => {
dispatch({type: AUTH_USER});
console.log(response);
localStorage.setItem('token', response.data.token);
cb();
})
.catch(() => {
dispatch(authError('bad login info'));
})
}
}
can you try this, this should work.
this.history.pushState(null, '/posts');
if you are using browserHistory
this.context.router.push('/posts'); or browserHistory.push('/login');
One way to do it is that somewhere in state you have item "isLoggedin" or something like that. If that item is false, you you render login route normally with edit boxes to enter user info. when isLoggedIn in state changes to true, you render your login route to something like this:
<Redirect to="/posts"/>
and off you go!