So i want to be able to go to the main page after the user successfully logs in. I am still new to React. How can this be done. I am using v4 of react as well. When i hit the login button it seems to trigger the action but not complete it.
Here is the action that handles the login:
const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
this.props.history.push('/main');
}
dispatch({
type: POST_DATA_SUCCESS,
response,
});
};
export function loginUser(username1, password1) {
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
username: username1,
password: password1,
})
});
return {
onRequest: POST_DATA_TRIGGERED,
onSuccess: mainPage,
onFailure: POST_DATA_FAILURE,
promise,
};
}
Here is the backend that handles the login request:
router.get('/login',
passport.authenticate('basic', {session: false}),
(req, res) => res.json({user: req.user.apiRepr()})
);
router.post('/login', function (req, res, next) {
passport.authenticate('basic', function (err, user, info) {
if (err) {
return console.log(err);
}
if (!user) {
return res.status(401).json({
message: 'Username/Password Incorrect'
});
}
req.logIn(user, function (err) {
if (err) {
return console.log(err);
}
return res.status(200).json({
user: user.username
});
});
})(req, res, next);
});
And the login component with the form:
import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';
export class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
//username: '',
//password: '',
}
}
render() {
return(
<form>
<h3>Login to start your Journey</h3>
<input placeholder="username" ref={input => {this.username = input}}>
</input>
<input placeholder="password" type="password"ref={input => {this.password
= input}}></input>
<button onClick={this.login.bind(this)}>Login</button>
</form>
)
}
login() {
const userName = this.username.value;
const passWord = this.password.value;
console.log(userName);
console.log(passWord);
this.props.loginUser(userName, passWord);
}
}
export default connect(null, { loginUser })(Login);
via JontheNerd
No comments:
Post a Comment