ReactJS Simple Project with MySQL and PHP – Part 2

Steps:

1. Create Signup.js with the following code under Signup folder.


import React, {Component} from 'react';
import {PostData} from '../../services/PostData';
import {Redirect} from 'react-router-dom';
class Signup extends Component {
constructor(props){
super(props);
this.state = {
username: '',
password: '',
email: '',
name: '',
redirectToReferrer: false
};
this.signup = this.signup.bind(this);
this.onChange = this.onChange.bind(this);
}

signup() {
if(this.state.username && this.state.password && this.state.email && this.state.name){
PostData('signup',this.state).then((result) => {
let responseJson = result;
if(responseJson.userData){
sessionStorage.setItem('userData',JSON.stringify(responseJson));
this.setState({redirectToReferrer: true});
}
else
alert(result.error);
});
}
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
}
render() {
if (this.state.redirectToReferrer || sessionStorage.getItem('userData')) {
return (<Redirect to={'/home'}/>)
}
return (
<div className="row " id="sBody">
<div className="medium-5 columns left">
<h4>Signup</h4>
<input type="text" name="email" placeholder="Email" onChange={this.onChange}/>
<input type="text" name="name" placeholder="Name" onChange={this.onChange}/>
<input type="text" name="username" placeholder="Username" onChange={this.onChange}/>
<input type="password" name="password" placeholder="Password" onChange={this.onChange}/>
<input type="submit" className="button" value="Sign Up" onClick={this.signup}/>
<a href="/login">Login</a>
</div>
</div>
);
}
}
export default Signup;

2. Create Login.js with the following code under Login folder.

import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import {PostData} from '../../services/PostData';
class Login extends Component {
constructor(){
super();
this.state = {
username: '',
password: '',
redirectToReferrer: false
};
this.login = this.login.bind(this);
this.onChange = this.onChange.bind(this);
}
login() {
if(this.state.username && this.state.password){
PostData('login',this.state).then((result) => {
let responseJson = result;
if(responseJson.userData){
sessionStorage.setItem('userData',JSON.stringify(responseJson));
this.setState({redirectToReferrer: true});
}
else
alert(result.error);
});
}
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
}
render() {
if (this.state.redirectToReferrer) {
return (<Redirect to={'/home'}/>)
}
if(sessionStorage.getItem('userData')){
return (<Redirect to={'/home'}/>)
}
return (
<div className="row" id="Body">
<div className="medium-5 columns left">
<h4>Login</h4>
<input type="text" name="username" placeholder="Username" onChange={this.onChange}/>
<input type="password" name="password" placeholder="Password" onChange={this.onChange}/>
<input type="submit" className="button" value="Login" onClick={this.login}/>
<a href="/signup">Registration</a>
</div>
</div>
);
}
}
export default Login;

3. Create Home.css with the following code under Home folder.

.logout{
float:right;
margin:10px 0px;
}

4. Create Home.js with the following code under Home folder.

import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import './Home.css';
import {PostData} from '../../services/PostData';
//import UserFeed from "../UserFeed/UserFeed";
import { confirmAlert } from 'react-confirm-alert';
import '../../styles/react-confirm-alert.css';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:[],
userFeed: '',
redirectToReferrer: false,
name:'',
};
this.getUserFeed = this.getUserFeed.bind(this);
this.feedUpdate = this.feedUpdate.bind(this);
this.onChange = this.onChange.bind(this);
this.deleteFeed = this.deleteFeed.bind(this);
this.editFeed = this.editFeed.bind(this);
this.deleteFeedAction = this.deleteFeedAction.bind(this);
this.logout = this.logout.bind(this);
}

componentWillMount() {
if(sessionStorage.getItem("userData")){
this.getUserFeed();
}
else{
this.setState({redirectToReferrer: true});
}
}

feedUpdate(e) {
e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed };
if (this.state.userFeed) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}

deleteFeed(e){
confirmAlert({
title: 'Delete Feed',
message: 'Are you sure to delete this feed.',
buttons: [
{
label: 'Yes',
onClick: () => this.deleteFeedAction(e)
},
{
label: 'No',
//onClick: () => alert('Click No')
}
]
});
}

deleteFeedAction(e){
let updateIndex=e.target.getAttribute('value');
let feed_id=document.getElementById("del").getAttribute("data");
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id,feed_id: feed_id };
if (postData) {
PostData('feedDelete', postData).then((result) => {
this.state.data.splice(updateIndex,1);
this.setState({data:this.state.data});
if(result.success){
alert(result.success);
}
else
alert(result.error);
});
}
}

getUserFeed() {
let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
let postData = { user_id: data.userData.user_id};
if (data) {
PostData('feed', postData).then((result) => {
let responseJson = result;
if(responseJson.feedData){
this.setState({data: responseJson.feedData});
console.log(this.state);
}
});
}
}
onChange(e){
this.setState({userFeed:e.target.value});
}

logout(){
sessionStorage.setItem("userData",'');
sessionStorage.clear();
this.setState({redirectToReferrer: true});
}

render() {
if (this.state.redirectToReferrer) {
return (<Redirect to={'/login'}/>)
}

return (
<div className="row" id="Body">
<div className="medium-12 columns">
<a href="#" onClick={this.logout} className="logout">Logout</a>
<form onSubmit={this.feedUpdate} method="post">
<input name="userFeed" onChange={this.onChange} value={this.state.userFeed} type="text" placeholder="Write your feed here..."/>
<input type="submit" value="Post" className="button" onClick={this.feedUpdate}/>
</form>
</div>

</div>
);
}
}
export default Home;

5. Modify the routes.js


import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Welcome from '././components/Welcome/Welcome';
import Home from '././components/Home/Home';
import Login from '././components/Login/Login';
import Signup from '././components/Signup/Signup';
import NotFound from '././components/NotFound/NotFound';

const Routes = () => (
<BrowserRouter >
<Switch>
<Route exact path="/" component={Welcome}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/Signup" component={Signup}/>
<Route path="*" component={NotFound}/>
</Switch>
</BrowserRouter>
);
export default Routes;

6. Add PostData.js under services folder.

export function PostData(type, userData) {
let BaseURL = 'http://localhost/react-php/api/index.php';
return new Promise((resolve, reject) =>{

fetch(BaseURL+'?tp='+type,
{

method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body:JSON.stringify(userData)
})
.then((response) => response.json()
.then((res) => {
resolve(res);
}))
.catch((error) => {
reject(error);
});
});
}

7. Run the app from the browser.

The steps are shown in the following video.

Next