[ad_1]
Asked
Viewed
5 times
I first take my time to thank you for reading this. I am desperately in need of your help. I know there are many questions out there that are similar to this and have been answered but I tried my best to follow them all. Nothing worked, so I would like a direct answer to my problem via this post. Refer to this and you will know what I’m talking about: https://youtu.be/FX5HE_gnOTI
I have a couple problems that may be related to one and another. So I followed mostly what the guy in the video did but there is a problem in my work that says otherwise: When I hit the VIEW button, the information submitted doesn’t populate. When I hit the DELETE button, it does not delete the item. (I have to manually send a request via Postman Agent and refresh the browser to see it delete.) And when I hit the EDIT button, it would not save and go back the main page when I hit SAVE. I have spent hours researching and debugging but none of them worked. Your help will be much appreciated and a huge thank you (I deeply mean it), if you managed to help me fix it.
The console of my application.
import React, { Component } from 'react'
import StudentService from '../services/StudentService';
class UpdateStudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
this.changeFirstName = this.changeFirstName.bind(this);
this.changeLastName = this.changeLastName.bind(this);
this.changeEmail = this.changeEmail.bind(this);
this.updateStudent = this.updateStudent.bind(this);
}
componentDidMount() {
StudentService.getStudentId(this.state.id).then((res) => {
let student = res.data;
this.setState
({firstName: student.firstName,
lastName: student.lastName,
emailId: student.emailId
});
});
}
updateStudent = (e) => {
e.preventDefault();
let student = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('student => ' + JSON.stringify(student));
console.log('id => ' + JSON.stringify(this.state.id));
StudentService.updateStudent(student, this.state.id).then(res => {
this.props.history.push('/students');
});
}
changeFirstName = (event) => {
this.setState({firstName: event.target.value});
}
changeLastName = (event) => {
this.setState({lastName: event.target.value});
}
changeEmail = (event) => {
this.setState({emailId: event.target.value});
}
cancel() {
this.props.history.push('/students');
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
<h3 className="text-center">Update Student</h3>
<div className = "card-body">
<form>
<div className = "form-group">
<label> First Name: </label>
<input placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstName}/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastName}/>
</div>
<div className = "form-group">
<label> Email Id: </label>
<input placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmail}/>
</div>
<button className="btn btn-success" onClick={this.updateStudent}> Save </button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}> Cancel </button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default UpdateStudentComponent
import React, { Component } from 'react'
import StudentService from '../services/StudentService'
class ListStudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
students: []
}
this.addStudent = this.addStudent.bind(this);
this.editStudent = this.editStudent.bind(this);
this.deleteStudent = this.deleteStudent.bind(this);
}
deleteStudent(id) {
StudentService.deleteStudent(id).then(res => {
this.setState({students: this.state.students.filter(student => student.id !== id)});
}).catch(error => console.log(error));
}
viewStudent(id){
this.props.history.push(`/view-student/${id}`);
}
editStudent(id){
this.props.history.push(`/add-student/${id}`);
}
componentDidMount(){
StudentService.getStudents().then((res) => {
this.setState({students: res.data});
});
}
addStudent(){
this.props.history.push('/add-student/_add');
}
render() {
return (
<div>
<h2 className="text-center">Students List</h2>
<div className = "row">
<button className="btn btn-primary" onClick={this.addStudent}> Add Student </button>
</div>
<br></br>
<div className = "row">
<table className = "table table-striped table-bordered">
<thead>
<tr>
<th> Student First Name</th>
<th> Student Last Name</th>
<th> Student Email Id</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
{
this.state.students.map(
student =>
<tr key = {student.id}>
<td> {student.firstName} </td>
<td> {student.lastName}</td>
<td> {student.emailId}</td>
<td>
<button onClick={ () => this.editStudent(student.id)} className="btn btn-success"> Edit </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.deleteStudent(student.id)} className="btn btn-danger"> Delete </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.viewStudent(student.id)} className="btn btn-info"> View </button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
)
}
}
export default ListStudentComponent
import React, { Component } from 'react'
import StudentService from '../services/StudentService'
class ViewStudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
student: []
}
}
componentDidMount() {
StudentService.getStudentById(this.state.id).then(res => {
this.setState({student: res.data});
})
}
render() {
return (
<div>
<br></br>
<div className = "card col-md-6 offset-md-3">
<h3 className = "text-center"> View Student Details </h3>
<div className = "card-body">
<div className = "row">
<label> Student First Name: </label>
<div> {this.state.student.firstName} </div>
</div>
<div className = "row">
<label> Student Last Name: </label>
<div> {this.state.student.lastName} </div>
</div>
<div className = "row">
<label> Student Email ID: </label>
<div> {this.state.student.emailId} </div>
</div>
</div>
</div>
</div>
)
}
}
export default ViewStudentComponent
import axios from 'axios';
const STUDENT_API_BASE_URL = "http://localhost:8080/api/v1/students";
class StudentService {
getStudents() {
return axios.get(STUDENT_API_BASE_URL);
}
createStudent(student) {
return axios.post(STUDENT_API_BASE_URL, student);
}
getStudentById(studentId) {
return axios.get(STUDENT_API_BASE_URL + "https://stackoverflow.com/" + studentId);
}
updateStudent(student, studentId) {
return axios.put(STUDENT_API_BASE_URL + "https://stackoverflow.com/" + studentId, student);
}
deleteStudent(studentId) {
return axios.delete(STUDENT_API_BASE_URL + "https://stackoverflow.com/" + studentId);
}
}
export default new StudentService()
package com.studentroster.springboot.controller;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.studentroster.springboot.exception.ResourceNotFoundException;
import com.studentroster.springboot.model.Students;
import com.studentroster.springboot.repository.StudentRepository;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/api/v1/")
public class StudentController {
@Autowired
private StudentRepository stud_rep;
// GET all students
@GetMapping("/students")
public List<Students> getAllStudents() {
return stud_rep.findAll();
}
// ADD student
@PostMapping("/students")
public Students addStudent(@RequestBody Students student) {
return stud_rep.save(student);
}
// Get Student ID
@GetMapping("/students/{id}")
public ResponseEntity<Students> getStudentId(@PathVariable Long id) {
Students stud = stud_rep.findById(id).orElseThrow(() -> new ResourceNotFoundException("Student does not exist with the id: " + id));
return ResponseEntity.ok(stud);
}
// UPDATE student
@PutMapping("/students/{id}")
public ResponseEntity<Students> updateStudent(@PathVariable Long id, @RequestBody Students studentDetails) {
Students stud = stud_rep.findById(id).orElseThrow(() -> new ResourceNotFoundException("Student does not exist with the id: " + id));
stud.setFirstName(studentDetails.getFirstName());
stud.setLastName(studentDetails.getLastName());
stud.setEmail(studentDetails.getEmail());
Students studentUpdated = stud_rep.save(stud);
return ResponseEntity.ok(studentUpdated);
}
// DELETE student
@DeleteMapping("/students/{id}")
public ResponseEntity<Map<String, Boolean>> deleteStudent(@PathVariable Long id) {
Students stud = stud_rep.findById(id).orElseThrow(() -> new ResourceNotFoundException("Student does not exist with the id: " + id));
stud_rep.delete(stud);
Map<String, Boolean> response = new HashMap<>();
response.put("Deleted", Boolean.TRUE);
return ResponseEntity.ok(response);
}
}
{
"name": "react-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"bootstrap": "^4.5.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
import React from 'react';
import logo from './logo.svg';
import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import ListStudentComponent from './components/ListStudentComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
import CreateStudentComponent from './components/CreateStudentComponent';
import UpdateStudentComponent from './components/UpdateStudentComponent';
import ViewStudentComponent from './components/ViewStudentComponent';
function App() {
return (
<div>
<Router>
<HeaderComponent />
<div className="container">
<Switch>
<Route path = "https://stackoverflow.com/" exact component = {ListStudentComponent}></Route>
<Route path = "/students" component = {ListStudentComponent}></Route>
<Route path = "/add-student/:id" component = {CreateStudentComponent}></Route>
<Route path = "/view-student/:id" component = {ViewStudentComponent}></Route>
<Route path = "/update-student/:id" component = {UpdateStudentComponent}></Route>
</Switch>
</div>
<FooterComponent />
</Router>
</div>
);
}
export default App;
I have posted all the necessary files. Please let me know if you have any further questions and I thank you from the bottom of my heart if you manage to fix my problem.
lang-js
[ad_2]