I have an issue with the login authentication in my project. I connected my react front end with my express back end, but when I try to login with valid credentials, it gets stuck in an error seems like it can't read properly the value I'm passing in my form input.
Here's my LogIn page:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { signin } from '../actions/authAction';
import { clearErrors } from '../actions/errAction';
import { Button, Form, FormGroup, Input, Alert } from 'reactstrap'
import TopCont from '../components/TopCont'
class Signin extends Component {
state = {
email: '',
password: '',
msg: null
};
static propTypes = {
isAuth: PropTypes.bool,
signin: PropTypes.func.isRequired,
err: PropTypes.object.isRequired,
clearErrors: PropTypes.object.isRequired
};
componentDidMount(){
this.props.clearErrors();
}
componentDidUpdate(prevProps){
const { err } = this.props;
if(err !== prevProps.err) {
if(err.id === 'LOGIN_FAIL'){
this.setState({ msg: err.msg.msg });
} else {
this.setState({ msg: null });
}
}
};
onChange = e => {
this.setState({
[e.target.email]: e.target.value,
[e.target.password]: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
const { email, password } = this.state;
const user = {
email,
password
};
this.props.signin(user);
/* this.props.push('/dashboard'); */
};
render() {
return (
<>
<TopCont>
<div className="signin-cont">
<h1>Accedi</h1>
{this.state.msg ? <Alert color="danger">{this.state.msg}</Alert> : null }
<Form className="signin-form-cont" onSubmit={this.onSubmit}>
<FormGroup>
<Input className="signin-form" type="email" name="email" id="email" placeholder="mario.rossi#prova.it" onChange={this.onChange}/>
</FormGroup>
<FormGroup>
<Input className="signin-form" type="password" name="password" id="password" placeholder="Password" onChange={this.onChange}/>
</FormGroup>
<Button className="sign-btn">Accedi</Button>
</Form>
<p>Non hai ancora un account? <Link to="/signup">Registrati</Link></p>
</div>
</TopCont>
</>
)
}
}
const mapStateToProps = state => ({
isAuth: state.auth.isAuth,
err: state.err
});
export default connect(mapStateToProps, { signin, clearErrors })(Signin);
Here is my Action:
import axios from 'axios';
import { returnErrors } from './errAction';
import { AUTH_ERROR, LOGIN_FAIL } from '../actions/types';
export const signin = ({ email, password }) => dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email, password });
axios.post('/api/auth', body, config)
.then(res => dispatch({
type: LOGIN_SUCCESS,
payload: res.data
}))
.catch(err => {
dispatch(returnErrors(err.response.data, err.response.status, 'LOGIN_FAIL'));
dispatch({
type: LOGIN_FAIL
});
});
};
And here is my Auth API:
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const config = require('config');
const jwt = require('jsonwebtoken');
const auth = require('../../middleware/auth');
const User = require('../../models/User');
//#action POST api/auth
//#descr auth user
//#access Public
router.post('/', (req, res) => {
const { email, password } = req.body
if( !email || !password ) {
return res.status(400).json({ msg: "Enter all fields."});
}
User.findOne({ email })
.then(user => {
if(!user) return res.status(400).json({ msg: "Nessun profilo trovato con questa email"});
bcrypt.compare( password, user.password )
.then(isMatch => {
if(!isMatch) return res.status(400).json({ msg: "Password errata!"});
jwt.sign(
{ id: user.id },
config.get('jwtSecret'),
{ expiresIn: 10800 },
(err, token) => {
if(err) throw err;
res.json({
token,
user: {
id: user.id,
name: user.name,
surname: user.surname,
email: user.email,
userPlus: user.userPlus
}
})
}
)
})
})
});
//#action GET api/auth/user
//#descr GET user data
//#access Private
router.get('/user', auth, (req, res) => {
User.findById(req.user.id)
.select('-password')
.then(user => res.json(user));
});
module.exports = router;
If I try to get rid of all the errors controls my server return this error:
TypeError: Cannot read property 'password' of null
The strange thing is that if I try to register a new user (with an almost identical component and server-side method) there are no problems and it authenticates too with no problems.
Someone knows how can I fix this issue?
Change your onChange Function from this:
onChange = e => {
this.setState({
[e.target.email]: e.target.value,
[e.target.password]: e.target.value
});
};
to this:
onChange = e => this.setState(prevState => ({
...prevState,
[e.target.name]: e.target.value,
}));
Related
I'm trying to return a value from my handleRegister function, but it gives me undefined, I checked before returning the value and it exists but as soon as I return, it's undefined. Can someone please help me? The object exists:
{
"signup": {
"name": "riced",
"id": 7135,
"email": "riced#gmail.com",
"password": "U24jg2xwSbF4R6k",
"error": null,
"__typename": "User"
}
}
The following part fails:
handleRegister(this.state).then(
(data) => {
console.log(data);
return;
});
import * as React from "react"
import { navigate } from "gatsby"
import {isLoggedIn } from "../services/auth"
import fetch from 'isomorphic-fetch';
import {ApolloClient, HttpLink, InMemoryCache, gql} from '#apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
uri: 'http://10.0.0.212:9000/',
fetch
})
});
export const REGISTER_USER = gql
mutation Mutation($signupInput: SignUpInput) {
signup(signupInput: $signupInput) {
name
id
email
password
error
}
}
;
export async function handleRegister ({ username, email, password }) {
/*
if (username === `john` && password === `pass`) {
return setUser({
username: `john`,
name: `Johnny`,
email: `johnny#example.org`,
})
*/
/*
client.query({ query: ALL_USERS }).then(result => console.log(result));
*/
//let [errors, setErrors] = React.useState([]);
var gottenToken = "";
//let gottenName;
await client.mutate({ mutation: REGISTER_USER, variables: {
"signupInput": {
"name": username,
"password": password,
"email": email,
}
} }).then(result => {
console.log(result);
console.log(result.data!.signup);
//let signup = JSON.stringify(result.data!.signup);
return result.data!.signup
//Promise.resolve(result.data!.signup);
}).catch(err => {
console.log(err);
//setUser({})
//React.useEffect(() => {
//localStorage.setItem('signupError', JSON.stringify(err));
//}, [errors]);
//return haveErrorOccured("Signing up error"); // send error to browser
});
//return haveErrorOccured("Signing up error"); // send error to browser
}
class Register extends React.Component {
state = {
username: ``,
email: ``,
password: ``,
}
handleUpdate = async event => {
await this.setState({
[event.target.name]: event.target.value,
})
}
handleSubmit = async event => {
event.preventDefault()
//handleRegister(this.state)
/*
handleRegister(this.state).then(r => {
console.log(r);
}).catch(err => {
console.log(err);
});
*/
handleRegister(this.state).then(
(data) =>{
console.log(data);
return;
//return 43;
});
//console.log("signed up: " + signup);
//console.table(signup);
}
render() {
if (isLoggedIn()) {
navigate(`/app/profile`)
}
//let errorSignup;
//if(window.localStorage.getItem("signupError")){
// errorSignup = JSON.stringify(JSON.parse(window.localStorage.getItem("signupError")));
//}
//navigate("/app/register?registered", { state: { foo: "bar" }});
//<p>{errorSignup}</p>
return (
<>
<h1>Register</h1>
<form
method="post"
onSubmit={event => {
this.handleSubmit(event);
}}
>
<label>
Username
<input type="text" name="username" onChange={this.handleUpdate} />
</label>
<label>
Email
<input type="text" name="email" onChange={this.handleUpdate} />
</label>
<label>
Password
<input
type="password"
name="password"
onChange={this.handleUpdate}
/>
</label>
<input type="submit" value="Log In" />
</form>
</>
)
}
}
export default Register
In this page the user can login, but if the untilDate is bigger than the current date it should log out the user. The code runs fine 1/2 times, the other giving me the error on the title.
I am working with createContext for user login. This is the AuthContext file
import React from "react";
import { createContext, useEffect, useReducer } from "react";
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
loading: false,
error: null,
};
export const AuthContext = createContext(INITIAL_STATE);
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN_START":
return {
user: null,
loading: true,
error: null,
};
case "LOGIN_SUCCESS":
return {
user: action.payload,
loading: false,
error: null,
};
case "LOGOUT":
return {
user: null,
loading: false,
error: null,
};
case "LOGIN_FAILURE":
return {
user: null,
loading: false,
error: action.payload,
};
case "UPDATE_USER_DATE":
const updatedUser = { ...state.user };
updatedUser.activeUntil = action.payload;
return {
...state,
user: updatedUser,
};
default:
return state;
}
};
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.user));
}, [state.user]);
return (
<AuthContext.Provider
value={{
user: state.user,
loading: state.loading,
error: state.error,
dispatch,
}}
>
{children}
</AuthContext.Provider>
);
};
When the user clicks the login button, it runs the handleClick function:
const handleClick = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
let date = new Date().toJSON();
let userdate = date;
try {
const res = await axios.post("/auth/signin", credentials);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
userdate = user.activeUntil;
//do if date is <=current datem dispatch logout
} catch (err) {
if (userdate > date) {
console.log("undefined data");
} else {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
}
}
if (userdate > date) {
dispatch({ type: "LOGOUT" });
console.log("If you are seeing this your contract has expired");
} else {
// navigate("/myinfo");
}
};
The console error happens from this line dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
Is there a way I can bypass this error or a different way I can write my code to make it work?
This is the full code of login page
import React from "react";
import axios from "axios";
import { useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import { AuthContext } from "../../context/AuthContext";
import {
Container,
FormWrap,
FormContent,
Form,
FormInput,
FormButton,
Icon,
FormH1,
SpanText,
IconWrapper,
IconL,
} from "./signinElements";
import Image from "../../images/Cover.png";
const Login = () => {
const [credentials, setCredentials] = useState({
namekey: undefined,
password: undefined,
});
/* */
// to view current user in console
const { user, loading, error, dispatch } = useContext(AuthContext);
let msg;
const navigate = useNavigate();
const handleChange = (e) => {
setCredentials((prev) => ({ ...prev, [e.target.id]: e.target.value }));
};
const handleClick = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
let date = new Date().toJSON();
let userdate = date;
try {
const res = await axios.post("/auth/signin", credentials);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
userdate = user.activeUntil;
//do if date is <=current datem dispatch logout
} catch (err) {
if (userdate > date) {
console.log("undefined data");
} else {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
}
}
if (userdate > date) {
dispatch({ type: "LOGOUT" });
console.log("If you are seeing this your contract has expired");
} else {
// navigate("/myinfo");
}
};
// console.log(user.activeUntil); //type to view current user in console
return (
<>
<Container>
<IconWrapper>
<IconL to="/">
<Icon src={Image}></Icon>
</IconL>
</IconWrapper>
<FormWrap>
<FormContent>
<Form action="#">
<FormH1>
Sign in with the namekey and password written to you on your
contract.
</FormH1>
<FormInput
type="namekey"
placeholder="Namekey"
id="namekey"
onChange={handleChange}
required
/>
<FormInput
type="password"
placeholder="Password"
id="password"
onChange={handleChange}
/>
<FormButton disabled={loading} onClick={handleClick}>
Login
</FormButton>
<SpanText>{msg}</SpanText>
{error && <SpanText>{error.message}</SpanText>}
{error && (
<SpanText>
Forgot namekey or password? Contact our support team +355 69
321 5237
</SpanText>
)}
</Form>
</FormContent>
</FormWrap>
</Container>
</>
);
};
export default Login;
The problem was i was trying to call a localy stored user and 1 time it wasnt loaded and the other it was. Simply fixed it by changing the if statement to check directly in result details without having to look in local storage.
const [expired, setExpired] = useState(false);
const handleClick = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/auth/signin", credentials);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
let date = new Date().toJSON();
if (res.data.details.activeUntil < date) {
dispatch({ type: "LOGOUT" });
console.log("Users contract has expired");
setExpired(!expired);
} else {
navigate("/myinfo");
}
} catch (err) {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data });
}
};
I want to change password, while I'm logged in.
Here's my function:
authActions.js(without catch because that will be implemented if anything start to works)
// Change password
export const changePassword = (newPassword) => (dispatch, getState) => {
// Headers
const config = {
headers: {
'Content-Type': 'application/json'
}
}
axios.post(`/api/auth/user/changePassword/`, newPassword, tokenConfig(getState))
.then(res => dispatch({
type: CHANGE_PASSWORD,
payload: res.data
}))
}
// Setup config/headers and token
export const tokenConfig = getState => {
// Get token from localstorage
const token = getState().auth.token;
// Headers
const config = {
headers: {
// "Accept": "application/json, multipart/form-data"
"Content-type": "application/json"
}
}
// If token, add to headers
if (token) {
config.headers['x-auth-token'] = token;
}
return config;
}
and authReducer.js:
...
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: false,
user: null
};
export default function (state = initialState, action) {
switch (action.type) {
...
case CHANGE_PASSWORD:
return {
...state,
token: null,
user: action.payload,
isAuthenticated: false,
isLoading: false
};
default:
return state;
}
}
and routes/api/auth.js
router.post('/user/changePassword/', (req, res) => {
console.log(req.body);
const { email, oldPassword, newPassword } = req.body
// find if old password is valid
User.findOne({ email })
.then(user => {
bcrypt.compare(oldPassword, user.password)
.then(isMatch => {
if (isMatch) {
// change to new password
user.password = newPassword
user
.save()
.then(newUser => {
res.status(200).send(newUser)
})
.catch(err => {
const message = err.message
res.status(500).json({
status: "change password failed",
msg: message
})
})
} else {
return res.status(401).send("Invalid old password")
}
})
})
.catch(err => {
res.status(500).send(err)
})
});
I have console.log(req.body); in routes just to check if anything works, but it don't works(didn't give me any message).
And component in the end(but it's not the source of problem):
import React, { useState, useEffect } from 'react';
import {
Button,
Modal,
ModalHeader,
ModalBody,
Form,
FormGroup,
Label,
Input,
NavLink
} from 'reactstrap';
import { connect } from 'react-redux';
import { changePassword } from '../../actions/authActions';
import PropTypes from 'prop-types';
const ChangePassword = ({ auth }) => {
const [modal, setModal] = useState(false);
const [enterPassword, setEnterPassword] = useState({
oldPassword: '',
newPassword: ''
});
const [takeEmail, setTakeEmail] = useState(null);
useEffect(() => {
const createArray = () => {
const { user } = auth;
setTakeEmail({ email: user.email });
};
createArray();
}, [auth.user]);
const toggle = () => {
setModal(!modal);
};
const onChange = e => {
setEnterPassword({
...enterPassword,
[e.target.name]: e.target.value
});
};
const onSubmit = (event) => {
event.preventDefault();
const { email } = takeEmail;
const { oldPassword, newPassword } = enterPassword;
console.log(enterPassword);
console.log(takeEmail);
const newUser = {
email,
oldPassword,
newPassword
}
// Add content via changePassword action
changePassword(newUser);
toggle();
}
return (
<div>
<NavLink onClick={toggle} href="#">
Change Password
</NavLink>
<Modal
isOpen={modal}
toggle={toggle}
className="open-modal"
>
<ModalHeader toggle={toggle}>Dodaj do listy ogłoszeń</ModalHeader>
<ModalBody>
<Form onSubmit={onSubmit}>
<FormGroup>
<Label for="oldPassword">Nagłówek</Label>
<Input
type="password"
name="oldPassword"
id="oldPassword"
placeholder="Wprowadź stare hasło..."
onChange={onChange}
/>
<Label for="newPassword">Nagłówek</Label>
<Input
type="password"
name="newPassword"
id="newPassword"
placeholder="Wprowadź stare hasło..."
onChange={onChange}
/>
<Button
color="dark"
style={{ marginTop: '2rem' }}
block>
Zmień hasło
</Button>
</FormGroup>
</Form>
</ModalBody>
</Modal>
</div>
);
}
ChangePassword.propTypes = {
isAuthenticated: PropTypes.bool,
changePassword: PropTypes.func.isRequired
}
const mapStateToProps = state => ({
auth: state.auth,
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, { changePassword })(ChangePassword);
This one particular firebase function hasn't worked for me when calling it as an action. Login, edit username, register, all of those work fine... except logout.
After looking at some tutorials and Google's own documentation, I thought this function would work like all the other firebase-auth functions I've implemented.
Here's what my actions to the db look like:
/* AuthUser.js */
export const login = credentials => {
return (dispatch, getState, { getFirebase }) => {
const firebase = getFirebase();
firebase
.auth()
.signInWithEmailAndPassword(credentials.email, credentials.password)
.then(() => {
dispatch({ type: LOGIN_SUCCESS });
dispatch(push('/home'));
})
.catch(err => {
dispatch({ type: LOGIN_FAIL, err });
});
};
};
export const logout = () => {
return (dispatch, getState, { getFirebase }) => {
const firebase = getFirebase();
firebase
.auth()
.signOut()
.then(() => {
dispatch({ type: LOGOUT_SUCCESS });
dispatch(push('/login'));
}) /* ERROR POINTS RIGHT AT THIS LINE */
.error(err => {
dispatch({ type: LOGOUT_FAIL, err });
});
};
};
export const register = user => {
return (dispatch, getState, { getFirebase }) => {
const firebase = getFirebase();
firebase
.auth()
.createUserWithEmailAndPassword(user.email, user.password)
.then(res => {
return res.user.updateProfile({
displayName: user.displayName,
});
})
.then(() => {
dispatch({ type: REGISTER_SUCCESS });
dispatch(push('/login'));
})
.catch(err => {
dispatch({ type: REGISTER_FAIL, err });
});
};
};
export const save = displayName => {
return (dispatch, getState, { getFirebase }) => {
const firebase = getFirebase();
const user = firebase.auth().currentUser;
if (displayName !== '') {
user
.updateProfile({
displayName,
})
.then(() => {
dispatch({ type: SETTINGS_NAME_CHANGED });
dispatch(push('/home'));
})
.catch(err => {
dispatch({ type: SETTINGS_ERROR, err });
});
} else {
dispatch({ type: SETTINGS_LEFT_ALONE });
dispatch(push('/home'));
}
};
};
Here is how I'm setting up my connects in the Component that calls some of these functions.
/* Settings.js */
import React from 'react';
import { /* Some Stuff */ } from 'reactstrap';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import 'someStyles.scss';
import { logout, save } from '../store/actions/authUser';
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
displayName: '',
};
}
/* This doesn't! */
onLogout = event => {
event.preventDefault();
this.props.logout();
};
/* This works! */
onSubmit = event => {
event.preventDefault();
this.props.save(this.state.displayName);
};
onChange = event => {
this.setState({
[event.target.id]: event.target.value,
});
};
render() {
const { displayName } = this.state;
return (
<Container className=".settingsBody">
<nav>
<Nav>
<NavItem>
<NavLink href="https://github.com">GitHub</NavLink>
</NavItem>
<NavItem>
<NavLink>
<div onClick={this.onLogout.bind(this)}>Logout</div>
</NavLink>
</NavItem>
</Nav>
</nav>
<Form onSubmit={this.onSubmit.bind(this)}>
<FormGroup>
<Label for="displayName">Change Display Name</Label>
<Input
type="text"
name="text"
id="displayName"
placeholder={this.props.auth.displayName}
value={displayName}
onChange={this.onChange}
/>
</FormGroup>
<Button color="primary">Save Settings</Button>
</Form>
</Container>
);
}
}
Settings.propTypes = {
logout: PropTypes.func.isRequired,
save: PropTypes.func.isRequired,
authError: PropTypes.string,
auth: PropTypes.object,
};
const mapStateToProps = state => {
return {
authError: state.auth.authError,
auth: state.firebase.auth,
};
};
const mapDispatchToProps = dispatch => {
return {
logout: () => dispatch(logout()),
save: displayName => dispatch(save(displayName)),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Settings);
React throws this error: TypeError: firebase.auth(...).signOut(...).then(...).error is not a function Yet other functions run as expected when ran.
Is there something I'm missing? The code will attempt to navigate to the page I want but throws the error before that page properly mounts.
Promises doesn't have .error callback, it should be .catch.
Read about Using Promises
Hi i am new in using react and axios. I have try the code for simple user CRUD, when i have successfully update the data, then the page will redirected to index of users (using this.props.history.push). The problem is the data is not immediately refreshed (data in index user is not updated) and need to refresh the page to show correctly the data. I have try the debug, then the componentDidMount, constructor, render called again properly but i see the problem in the axios get users method still return the old data. How to fix that? Thank you.
Here my IndexUser.js
// IndexUser.js
import React, { Component } from 'react';
import UserService from './UserService';
import axios from 'axios';
import UserRow from './UserRow';
class IndexUser extends Component {
constructor(props) {
super(props);
this.state = {value: '', users: ''};
this.addUserService = new UserService();
}
componentDidMount(){
axios.get('http://localhost:4200/users')
.then(response => {
this.setState({ users: response.data });
})
.catch(function (error) {
console.log(error);
})
}
userRow(){
if(this.state.users instanceof Object){
return this.state.users.data.map(function(object, i){
return <UserRow obj={object} key={i} />;
})
}
}
render() {
return (
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<td>User Id</td>
<td>Username</td>
<td>Password</td>
</tr>
</thead>
<tbody>
{this.userRow()}
</tbody>
</table>
</div>
);
}
}
export default IndexUser;
Here my EditUser.js:
// EditUser.js
import React, { Component } from 'react';
import axios from 'axios';
import UserService from './UserService';
class EditUser extends Component {
constructor(props) {
super(props);
this.state={user_id: this.props.match.params.user_id, username:'', password:''};
this.UserService = new UserService();
this.handleUsername = this.handleUsername.bind(this);
this.handlePassword = this.handlePassword.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
axios.get('http://localhost:4200/users/edit/'+this.props.match.params.user_id)
.then(response => {
if(response.data instanceof Object){
for(var key in response.data.data){
for(var subKey in response.data.data[key])
{
this.setState({[subKey]:response.data.data[key][subKey]});
}
}
}
})
.catch(function (error) {
console.log(error);
})
}
handleUsername(event){
this.setState({username:event.target.value});
}
handlePassword(event){
this.setState({password:event.target.value});
}
handleSubmit(event) {
this.UserService.updateData(this.state.username,this.state.password,this.props.match.params.user_id);
event.preventDefault();
this.props.history.push('/index');
}
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<label>
Edit Username:
<input type="text" value={this.state.username} onChange={this.handleUsername} className="form-control"/>
</label><br/>
<label>
Edit Password:
<input type="password" value={this.state.password} onChange={this.handlePassword} className="form-control"/>
</label><br/>
<input type="submit" value="Update" className="btn btn-primary"/>
</form>
</div>
);
}
}
export default EditUser;
Here my UserRow.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import UserService from './UserService';
class UserRow extends Component {
constructor(props) {
super(props);
this.addUserService = new UserService();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.addUserService.deleteData(this.props.obj.user_id);
}
render() {
return (
<tr>
<td>
{this.props.obj.user_id}
</td>
<td>
{this.props.obj.username}
</td>
<td>
{this.props.obj.password}
</td>
<td>
<Link to={"/edit/"+this.props.obj.user_id} className="btn btn-primary">Edit</Link>
</td>
<td>
<form onSubmit={this.handleSubmit}>
<input type="submit" value="Delete" className="btn btn-danger"/>
</form>
</td>
</tr>
);
}
}
export default UserRow;
Here my UserService:
//UserService.js
import axios from 'axios';
class UserService {
sendData(userId, username, password) {
axios.post('http://localhost:4200/users/add/user', {
userId: userId,
username: username,
password: password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
updateData(username,password, user_id){
axios.post('http://localhost:4200/users/update/'+user_id, {
username: username,
password: password
})
.then(res => this.setState({ users: res.data }))
.catch(err => console.log(err))
};
deleteData(user_id){
axios.get('http://localhost:4200/users/delete/'+user_id, {
})
.then(console.log('Deleted')).catch(err => console.log(err))
}
}
export default UserService;
This is my user routes server (using express + pg-promise):
// userRoutes.js
var express = require('express');
var app = express();
var userRouter = express.Router();
// Require User model in our routes module
var pgp = require('pg-promise')(/*options*/);
var db = pgp('postgres://postgres:ragamp#localhost:5433/coba');
//Index User
userRouter.route('/').get(function (req, res) {
db.any('select * from public.\"User\" ORDER BY user_id')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL Users'
});
})
.catch(function (err) {
});
});
//Insert User
userRouter.route('/add/user').post(function (req, res) {
db.none('INSERT INTO public.\"User\"(user_id, username, password) VALUES($1, $2, $3)', [req.body.userId, req.body.username, req.body.password])
.then(() => {
// success;
res.status(200)
.json({
status: 'success',
message: 'Insert One Users with username' + req.body.username
});
})
.catch(error => {
// error;
});
});
//Get one/Edit User
userRouter.route('/edit/:user_id').get(function (req, res) {
db.any('select * from public.\"User\" where user_id = $1', [req.params.user_id])
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL Users'
});
})
.catch(function (err) {
});
});
//Update User
userRouter.route('/update/:user_id').post(function (req, res) {
db.none('UPDATE public.\"User\" SET username = $1, password = $2 where user_id = $3', [req.body.username, req.body.password, req.params.user_id])
.then(() => {
// success;
res.status(200)
.json({
status: 'success',
message: 'Update One Users with username ' + req.body.username
});
})
.catch(error => {
// error;
});
});
//Delete User
userRouter.route('/delete/:user_id').get(function (req, res) {
db.none('DELETE FROM public.\"User\" WHERE user_id = $1', [req.params.user_id])
.then(() => {
// success;
res.status(200)
.json({
status: 'success',
message: 'Delete One Users with username ' + req.params.user_id
});
})
.catch(error => {
// error;
});
});
module.exports = userRouter;