Not able to delete my column from my Mysql table - mysql

I tried everything I think but no able to delete data from my mysql table using axios.delete with ProjectId (table ids).
Here's my code for where I declared my function, and as you can see I am passing the function through props
import React from "react";
import Projects from "../Projects/Projects";
import "./pluseProjects.css";
import {IoIosAddCircleOutline} from "react-icons/io"
import { Link } from "react-router-dom";
import {BiChevronLeftCircle,BiChevronRightCircle} from "react-icons/bi"
import {IoRefreshCircleOutline} from "react-icons/io5";
import axios from "axios";
export default function PluseProjects() {
const [addNewProjects, setAddNewProjects ] = React.useState(false)
const [getQuery,setGetQuery] = React.useState({
projectList:[]
})
function onStateChange() {
setAddNewProjects(!addNewProjects)
}
function getProjectList() {
axios.get(`http://localhost:3060/projects`)
.then((response) => response.data)
.then(response2 => {
setGetQuery({projectList : response2})
})
}
function onDeleteId(ProjectId) {
axios.delete(`http://localhost:3060/deleteprojects/${ProjectId}`)
getProjectList();
}
return(
<div className="Section-Projects" >
<div className="top-projects">
<h1>My Projects </h1>
<button onClick={getProjectList} className="Refresh"><IoRefreshCircleOutline /></button>
<Link to={addNewProjects?'/AddProjects':""} ><button className="Add-newProject" onClick={onStateChange}><IoIosAddCircleOutline /></button></Link>
</div>
<div className="Projects">
<button className="arrowLeft"><BiChevronLeftCircle /></button>
<div className="Single">
{getQuery.projectList.map((gettingQuery) =>
<Projects
onHandleDelete={onDeleteId(gettingQuery.ProjectId)}
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
)}
</div>
<button className="arrowRight"><BiChevronRightCircle /></button>
</div>
</div>
)
};
Here is my server.js code - I am telling SQL to delete this column with some ProjectId:
const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db = require('./Database')
const bodyParser = require('body-parser');
const { response } = require('express');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/projects', (req,res) => {
const TASK_QUERY = `SELECT * FROM newproject`;
db.query(TASK_QUERY , (err, response) => {
if(err) res.status(404).send('something is wrong')
else res.send(response)
})
});
app.post('/addProjects', (req,res) => {
const ADD_QUERY = `INSERT INTO newproject (ProjectName,Discription,git,Img) VALUES('${req.body.ProjectName}','${req.body.Discription}','${req.body.git}','${req.body.Img}')`;
db.query(ADD_QUERY, (err) => {
if (err) console.log(err)
else res.send('Query added successfully')
})
} );
app.delete('/deleteprojects/:ProjectId', (req,res) => {
console.log(req.params.ProjectId)
const DELETE_TASK = `DELETE FROM newProjects WHERE ProjectId = ${req.params.ProjectId}`
db.query(DELETE_TASK, (err,res) => {
if (err) console.log(err)
})
})
app.listen(PORT, () => {
console.log('app is listening on port 3000')
})
And here's where I am calling my function - I think my props management is all right. Am I calling the function the wrong way?
import React from "react";
import "./Projects.css"
import {RxCrossCircled} from "react-icons/rx"
export default function Projects(props) {
return(
<div className="Project" >
<div className="Image">
<img src={props.Img} alt=""/>
<button className="cross" onClick={props.ProjectId}><RxCrossCircled /></button>
</div>
<div className="Bottom">
<h3>{props.ProjectName}</h3>
<p>{props.Discription}</p>
{props.git}
</div>
</div>
)
};

If you see a http call in the network tab when you trigger the function (clicking the delete button etc). That means your frontend(react part) is working fine. Also i clearly see that you are missing an res.send() statement in your delete route in your server.js.
app.delete('/deleteprojects/:ProjectId', (req, res) => {
console.log(req.params.ProjectId)
const DELETE_TASK = `DELETE FROM newProjects WHERE ProjectId = ${req.params.ProjectId}`
db.query(DELETE_TASK, (err, res) => {
if (err) console.log(err)
res.status(200).send({}) // you missed this
})
})

Your onHandleDelete is not being used in the Projects component. And the ProjectId is not passed as a prop. In the PluseProjects you immediately call the onDeleteId function you should call it via an anonymous function.
PluseProjects
{
getQuery.projectList.map((gettingQuery) => (
<Projects
onHandleDelete={() => onDeleteId(gettingQuery.ProjectId)} // () =>
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
));
}
Projects
export default function Projects(props) {
return (
<div className="Project">
<div className="Image">
<img src={props.Img} alt="" />
<button className="cross" onClick={props.onHandleDelete}> // change ProjectId to onHandleDelete
<RxCrossCircled />
</button>
</div>
<div className="Bottom">
<h3>{props.ProjectName}</h3>
<p>{props.Discription}</p>
{props.git}
</div>
</div>
);
}

Related

Not able post data from useState to Mysql

I am trying to post the input data from useState to Mysql but its just not happening. While I am able to get the data from the database to the page but when it comes to posting I don't know how to send data from state hooks to mysql when there are many values. Please take a look
Code from where i am sending the form data
import React,{useState , useRef} from "react";
import "./AddProjects.css"
import axios from "axios";
import Projects from "../Projects/Projects";
import {BiChevronLeftCircle,BiChevronRightCircle} from "react-icons/bi"
export default function AddProjects() {
const [AddProjects,setAddProjects] = useState({
ProjectName:"",
Discription:"",
git:"",
Img:""
})
const [getQuery,setGetQuery] = useState({
projectList:[]
})
const inputFile = useRef(null)
function handleChange(e) {
const {name , value} = e.target;
setAddProjects(newProjects => ({
...newProjects,[name]:value
}))
}
function imgChange(e) {
setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
}
function getProjectList() {
axios.get(`http://localhost:3060/projects`)
.then((response) => response.data)
.then(response2 => {
setGetQuery({projectList : response2})
})
}
function onSubmitHandler(e) {
axios.post(`http://localhost:3060/addProjects`,{
ProjectName: AddProjects.ProjectName,
Discription:AddProjects.Discription,
git:AddProjects.git,
Img:AddProjects.Img
})
getProjectList()
}
return(
<>
<div className="AddProjects">
<form onSubmit={onSubmitHandler} method="POST" encType="multipart/form-data" >
<h2>Add New Project</h2>
<input type="text" placeholder="Project Name..." name="ProjectName" onChange={handleChange}/>
<input type="text" placeholder="Project Discription..." name="Discription" onChange={handleChange}/>
<input type="text" placeholder="Git Repository/Code..." name="git" onChange={handleChange}/>
<input type="file" accept="image/jpg,image/jpeg" name="Img" onChange={imgChange} ref={inputFile} />
<button type="button"onClick={() => inputFile.current.click()}>Add New Image</button>
<button type="submit" >Submit Project</button>
</form>
<button onClick={getProjectList}>click me </button>
</div>
<div>
<div className="Section-Projects" >
<h1>My Projects </h1>
{/* <Link to={checkBox?'/AddProjects':""} ><button className="Add-newProject" onClick={onStateChange}><IoIosAddCircleOutline/></button></Link> */}
<div className="Projects">
<button className="arrowLeft"><BiChevronLeftCircle /></button>
<div className="Single">
{getQuery.projectList.map((gettingQuery) =>
<Projects
ProjectId={gettingQuery.ProjectId}
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
)}
</div>
<button className="arrowRight"><BiChevronRightCircle /></button>
</div>
</div>
</div>
</>
)
};
As you can see i want to send 4 things to the mysql table but i don't think the this is the way to do it and i just can't figure it out
Code for my file that is sending data
const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db = require('./Database')
const bodyParser = require('body-parser');
const { response } = require('express');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/projects', (req,res) => {
const TASK_QUERY = `SELECT * FROM addprojects.newproject`;
db.query(TASK_QUERY , (err, response) => {
if(err) res.status(404).send('somthings wrong')
else res.send(response)
})
});
app.post('/addProjects', (req,res) => {
const ADD_QUERY = `INSERT INTO addprojects.newproject VALUES('${req.body.data}')`;
db.query(ADD_QUERY, (err) => {
if (err) console.log(err)
else res.send('Query added sucsessfully')
})
} );
app.listen(PORT, () => {
console.log('app is listning to port 3000')
})
I think while the post method is correct the Value is not so please help I am on this for 2 days Any suggestion will be help full
INSERT INTO tablename (columnName1, columnName2) VALUES ('Company Inc', 'Highway 37')
For backend:
You don't mention the columns name, it doesn't know which field belongs to which column in the table.
For Frontend:
axios.post(`http://localhost:3060/addProjects`,{
ProjectName: AddProjects.ProjectName,
Discription:AddProjects.Discription,
git:AddProjects.git,
Img:AddProjects.Img
})
ProjectName,Discription,git,Img make these keys name exact to your column names.
And you are uploading an image in this api so convert your data from front in formdata then pass that data in api and on backend you will that data in formdata

React server cannot acquire req.body.value from /get function. (but it works in post function)

I'm making a movie review app with React. I have an express server connecting to my localhost mySQL database. The connection and functions work but for some reason the req.body.value returns "undefined" in the app.get(/get) function but I get a working return in the app.post(/insert) function that is just right below that. The front-end function has the right value and it's showing in console.log just fine. What am I missing?
Express server:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express();
const mysql = require('mysql')
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "mymovies_jami"
});
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.json());
app.get('/get', (req, res) => {
console.log(req.body.username); /* This returns undefined*/
const username = req.body.username;
const sqlGet = `SELECT * FROM movie_reviews_${username} ORDER BY id DESC LIMIT 10`
connection.query(sqlGet, (err, result) => {
res.send(result)
console.log(err)
});
});
app.post('/insert', (req, res) => {
console.log(req.body.username); /* This works just fine*/
const username = req.body.username;
const movie_id = req.body.movie_id;
const movieName = req.body.movieName;
const movieComment = req.body.movieComment;
const movieWatched = req.body.movieWatched;
const poster_image = req.body.poster_image;
const sqlInsert = `INSERT INTO movie_reviews_${username} (movieName, movieComment, movieWatched, poster_image, movie_id) VALUES (?,?,?,?,?)`;
connection.query(sqlInsert, [movieName, movieComment, movieWatched, poster_image, movie_id], (err, result) => { console.log(err) });
});
Front-end GET:
import React from 'react';
import axios from 'axios';
import './style.css';
import { ModalDimmer } from 'semantic-ui-react';
class CrudGet extends React.Component {
state = { username: "jami", recentlyW: [], variable: 5, buttonText: 'Show more...', show: false }
componentDidMount() {
this.getMovies(this.state.recentlyW);
}
componentDidUpdate(recentlyW) {
if (this.state.recentlyW !== recentlyW) {
console.log(this.state.recentlyW)
}
}
getMovies = async () => {
const res = await axios.get('http://localhost:3301/get', {
username: this.state.username,
})
this.setState({ recentlyW: res.data })
}
render() {
const showMore = () => {
if (this.state.show === true) {
this.setState({ variable: 5 })
this.setState({ buttonText: "Show more..." })
this.setState({ show: false })
} else {
this.setState({ variable: 10 })
this.setState({ buttonText: "Show less..." })
this.setState({ show: true })
}
console.log(this.state.show)
}
const tmdb = 'https://www.themoviedb.org/movie/'
return (
<>{this.state.recentlyW ? (
<div >
{this.state.recentlyW.slice(0, `${this.state.variable}`).map(recent => (
<div className="item" key={recent.id}>
<details>
<img className='poster_recently' src={recent.poster_image} />
<summary> {recent.movieName}</summary>
<br></br>
<p></p>
<p>Comment: {recent.movieComment}</p>
<p>Watched: {recent.movieWatched?.substring(0, 10)}</p>
<p><a href={tmdb + recent.movie_id} target='_blank'>Movie in The Movie Database</a></p>
</details>
</div>
))
}<br /><button className='ui button' onClick={showMore}>{this.state.buttonText}</button>
</div>
) : (<div className='errormsg'><p className='error'>Could not connect to database. Check connection and username/password.</p></div>)
}</>
)
}
}
export default CrudGet;
Front-end INSERT:
import React from 'react';
import axios from 'axios';
import './style.css';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
import './style.css';
class CrudPost extends React.Component {
state = { movieName: '', movieComment: '', movieWatched: '', startDate: (new Date()), poster_image: '', username: '', movie_id: '' }
render() {
const nimivaihdos = () => {
this.setState({ username: getUser })
this.setState({ movieName: movie_name })
this.setState({ poster_image: movie_poster })
this.setState({ movie_id: movieID })
}
var getUser = window.localStorage.getItem('username')
var getUser = getUser.substring(1, getUser.length - 1)
var movie_poster = window.localStorage.getItem('movie_poster')
var movie_poster = movie_poster.substring(1, movie_poster.length - 1)
var movie_name = window.localStorage.getItem('movie_name')
var movie_name = movie_name.substring(1, movie_name.length - 1)
var movieID = window.localStorage.getItem('movie_id')
const submitReview = () => {
axios.post('http://localhost:3301/insert', {
username: this.state.username,
movie_id: this.state.movie_id,
movieName: this.state.movieName,
movieComment: this.state.movieComment,
movieWatched: this.state.movieWatched,
poster_image: this.state.poster_image
}).then(() => {
alert('Great success!')
})
}
return (
<div className='ui grid'>
<div className='two column row'>
<div className='column'>
<img className='poster' src={movie_poster} />
</div>
<div className='column'>
<form className='ui form'>
<div className='field'>Movie Name
<input type='text' placeholder={movie_name} onClick={nimivaihdos} onChange={(event) => this.setState({ movieName: event.target.value })}
value={this.state.movieName}></input>
</div>
<div className='field'>Comment
<textarea rows='2' placeholder='Write your movie comment' onChange={(event) => this.setState({ movieComment: event.target.value })}
value={this.state.movieComment}></textarea>
</div>
<div className='field'>Date watched
<DatePicker selected={this.state.startDate} onChange={(date) => this.setState({ startDate: date, movieWatched: date })} />
</div>
<button onClick={submitReview} className='ui button'>Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default CrudPost
GET requests should not have a body.
Change the method from 'GET' to 'POST'
or
use the params property
like so,
const res = await axios.get('http://localhost:3301/get', {
params: {
username: this.state.username
}
})
For more reference -> Axios get in url works but with second parameter as object it doesn't

Way to display individual data from MySQL database on React.js?

Is there a way that individual data from the MySQL database will be displayed on the react.js pages, like user profile?
This is my user profile but it display all the data on the database. How I can display single data? For example the information of the Student number 1. const getStudent is where the connection happen from the backend
Front end
import React from "react";
import { useState } from "react";
import Axios from "axios";
import { useNavigate } from "react-router-dom";
function Profile() {
const [studentList, setStudentList] = useState([]);
let navigate = useNavigate();
const getStudent = () => {
Axios.get("http://localhost:3001/students").then((response) => {
setStudentList(response.data);
});
};
return (
<div className="students">
<button onClick={getStudent}>Show Students</button>
<h3>
</h3>
{studentList.map((val, key) => {
return (
<div className="student">
<div>
<h3>Email: {val.email}</h3>
<h3>Password: {val.password}</h3>
<h3>Student Number: {val.student_num}</h3>
<h3>First Name: {val.first_name}</h3>
<h3>Middle Name: {val.middle_name}</h3>
<h3>Last Name: {val.last_name}</h3>
<h3>Year Level: {val.year_lvl}</h3>
<h3>Section: {val.section}</h3>
</div>
</div>
);
})}
</div>
);
}
export default Profile;
key is the name of the column
The connection of the mysql/ BackEnd
app.get("/students", (req, res) => {
db.query("SELECT * FROM student", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:
xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server
Error)
I have seen people asking about this but none of their solutions work for me!
I don't know if is something wrong in this component or I have something wrong with the server side.
import React, { Component } from "react";
import axios from "axios";
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePass = this.handleChangePass.bind(this);
}
handleChangeEmail = e => {
this.setState({ email: e.target.value });
//console.log(e.target.value);
};
handleChangePass = e => {
this.setState({ password: e.target.value });
//console.log(e.target.value);
};
handleSubmit = e => {
/*this.props.history.push('/');
console.log(this.props);*/
event.preventDefault();
let data = JSON.stringify({
email: this.state.email,
password: this.state.password
});
let url = "http://localhost:3000/dependentes";
const response = axios.post(url, data, {
headers: { "Content-Type": "application/json" }
});
};
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Log In</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
onChange={this.handleChangeEmail}
value={this.state.email}
/>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
onChange={this.handleChangePass}
/>
</div>
<div className="input-field">
<button className="btn orange lighten-1 z-depth-0">Log In</button>
</div>
</form>
</div>
);
}
}
export default LogIn;
According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.
Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.
So, to edit your code
//installed express, mysql, cors
const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line
const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';
const connection = mysql.createConnection(config.mysql);
connection.connect(err => {
if (err) {
return err;
}
});
app.get('/', (req, res) => {
res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
res.end();
});
app.get('/dependentes', (req, res) => {
connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
if (err) {
res.send(err);
} else {
res.json({
data: results
});
}
});
});
app.post('/dependentes', (req, res) => {
console.log(req.body.email);
res.json({ email: req.body.email }); ///<== and this line
});
app.listen(port, err => {
return err
? console.log(`error founded: ${err}`)
: console.log(`server runnning on port: ${port}`);
});

React Express MySQL CRUD operations Question?

I'm developing a basic to do list application utilizing Reactjs, Express, and a MySQL backend database. The application should create, read, update, and delete tasks. I have some questions regarding the update and delete operations. I want to be able to delete and update a task. I have not been able to figure out how to delete a so-called task. So far, I drafted DB's API plus routing for the delete operation within the server.js file and a click event logic within Overview.js component. But, I somehow cannot reference an id or a TASK_ID (AKA the PK) to send in the HTTP request. Refer to the onTaskDelete click event with the fetch API within Overview.js. Keep receiving "400 or Bad response from server" error. I believe, this is where the problem lies. How would I go about getting a delete task to work properly? Any help will be much appreciated! Thanks!
/* App.js */
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import './App.css';
import Scheduler from './Scheduler.js';
import Create from './Create.js';
import Modify from './Modify.js';
import Overview from './Overview.js';
import About from './About.js';
import NotFound from './NotFound.js';
import InternalServer from './InternalServer.js';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {tasks: [] };
}
componentDidMount() {
fetch('/tasks/get')
.then(response => response.json())
.then(response => this.setState({ tasks: response.data }))
.catch(error => console.error(error))
}
render() {
const { tasks } = this.state;
return (
<div className="App">
<Switch>
<Route exact path='/' render={() => (
<Scheduler tasks={tasks}/>
)}/>
<Route path='/create' render={() => (
<Create/>
)}/>
<Route path='/overview' render={() => (
<Overview tasks={tasks}/>
)}/>
<Route path='/about' render={() => (
<About/>
)}/>
<Route path="/500" component={InternalServer} status={500}/>
<Route path="*" component={NotFound} status={404}/>
</Switch>
</div>
);
}
}
export default App;
/* server.js */
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const selectAllTasks = 'SELECT * FROM TASKS';
const selectAllTasksByID = 'SELECT * FROM TASKS WHERE TASK_ID=?';
const selectAllProperties = 'SELECT * FROM PROPERTIES';
const insertTasks = 'INSERT INTO TASKS SET ?';
const delTasks = 'DELETE FROM TASKS WHERE TASK_ID=?';
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '******',
database: 'task_db'
});
conn.connect(error => {
if (error) throw error;
console.log(`Connected!`);
});
console.log(conn);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.get('/', (request, response) => {
response.send('Go to /tasks to see tasks data');
});
app.get('/tasks/get', (request, response) => {
conn.query(selectAllTasks, (error, results) => {
if (error) {
return response.send(error);
}
else {
return response.json({
data: results
})
}
});
});
app.get('/properties/get', (request, response) => {
conn.query(selectAllProperties, (error, results) => {
if (error) {
return response.send(error);
}
else {
return response.json({
data: results
})
}
});
});
app.post('/tasks/create', (request, response) => {
let data = {
TASK_NAME: request.body.Name,
TASK_DESC: request.body.Desc,
TASK_LOCATION: request.body.Location,
ASSIGNED_TO: request.body.Assign
};
conn.query(insertTasks, data, (error, results, fields) => {
if (error) {
return response.send(error);
}
else {
response.send(JSON.stringify(results));
}
});
});
app.put('/tasks/update', (request, response) => {
/* Need help drafting the code... */
response.send('Tasks update!');
});
app.get('/tasks/:TASK_ID', (request, response) => {
conn.query(selectAllTasksByID, request.params.TASK_ID, (error, results) => {
if (error) {
return response.send(error);
}
else {
response.send(JSON.stringify(results));
}
});
});
app.delete('/tasks/delete:TASK_ID', (request, response) => {
const Id = {id: request.params.TASK_ID};
conn.query(delTasks, [request.body.TASK_ID], Id, (error) => {
if (error) {
return response.send(error);
}
else {
request.flash('Task Deleted Successfully!!! ' + 'ID: ' + request.params.TASK_ID);
response.send(JSON.stringify(results));
response.redirect('/overview');
}
});
});
app.listen(4000, () => {
console.log(`Tasks server listening on port 4000`)
});
/* Overview.js */
import React from 'react';
import TaskBreadcrumb from './TaskBreadcrumb.js';
/* https://dev.to/abdulbasit313/an-easy-way-to-create-a-customize-dynamic-table-in-react-js-3igg */
/* https://www.w3schools.com/howto/howto_js_todolist.asp */
import DoneOutlineIcon from '#material-ui/icons/DoneOutline';
import NotificationsActiveIcon from '#material-ui/icons/NotificationsActive';
import EditIcon from '#material-ui/icons/Edit';
import DeleteIcon from '#material-ui/icons/Delete';
/*import Modal from 'react-modal';*/
import EditModal from './EditModal.js';
import {Helmet} from "react-helmet";
class Overview extends React.Component {
renderTaskData() {
const tasks = this.props.tasks;
return tasks.map(task =>
<tr key={task.TASK_ID}>
<td>{task.TASK_ID}</td>
<td>{task.TASK_NAME}</td>
<td>{task.TASK_DESC}</td>
<td>{task.TASK_LOCATION}</td>
<td>{task.TASK_COMPLETE}</td>
<td>{task.ASSIGNED_TO}</td>
<td>
<button id={task.TASK_ID} className="w3-button" title="Edit Task" onClick={this.onTaskEdit}> <EditIcon /> </button>
<button id={task.TASK_ID} className="w3-button" title="Delete Task" onClick={this.onTaskDelete(task.TASK_ID)}> <DeleteIcon /> </button>
<button id={task.TASK_ID} className="w3-button" title="Task complete" onClick={this.onTaskComplete}> <DoneOutlineIcon /> </button>
<button id={task.TASK_ID} className="w3-button" title="Task reminder" onClick={this.onTaskRemind}> <NotificationsActiveIcon /> </button>
</td>
</tr>
)
}
onTaskComplete() {
console.log("Task Complete!")
}
onTaskDelete(task) {
const tasks = this.props;
console.log("Task Deleted!")
let data = {
Id: task.TASK_ID
};
fetch('/tasks/delete:TASK_ID', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data){
if (data === "success") {
alert('Task record deleted successfully!')
}
}).catch(function(error){
console.log(error)
});
}
onTaskEdit() {
console.log("Task Edited!")
}
onTaskRemind() {
console.log("Task Reminder alert!")
}
render() {
return (
<div className="w3-container">
<Helmet>
<title>Reroot Task Scheduler - Task Overview</title>
</Helmet>
<TaskBreadcrumb/>
<div className="w3-card-4">
<div className="w3-container w3-green">
<h1 className="w3-animate-top">Task Overview:</h1>
</div>
<h3>Property Name:</h3>
<div className="w3-responsive">
<table className="w3-table-all w3-card-4 w3-hoverable w3-centered">
<thead>
<tr className="w3-pale-yellow">
<th>Task ID</th>
<th>Task Name</th>
<th>Task Description</th>
<th>Task Location</th>
<th>Status</th>
<th>Person responsible</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.renderTaskData()}
</tbody>
</table>
</div>
<EditModal/>
</div>
</div>
);
}
}
export default Overview;