Category : React JS | Sub Category : React JS | By Prasad Bonam Last updated: 2023-11-16 14:40:32 Viewed : 673
Implementing CRUD (Create, Read, Update, Delete) operations between a React front end and a Spring Boot back end involves several steps. Below, I will provide a simplified example for a basic entity (e.g., a "Task"):
Create Entity Class:
Create a simple entity class representing the data you want to CRUD. For example, a Task
class:
java@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String description;
// Getters and setters
}
Create Repository Interface: Create a repository interface to perform CRUD operations on the entity:
javapublic interface TaskRepository extends JpaRepository<Task, Long> {
}
Create Controller: Create a controller to handle HTTP requests:
java@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@Autowired
private TaskRepository taskRepository;
// CRUD endpoints (create, read, update, delete) go here
}
Implement CRUD Endpoints: Implement methods in the controller for each CRUD operation. For example:
java@PostMapping
public Task createTask(@RequestBody Task task) {
return taskRepository.save(task);
}
@GetMapping
public List<Task> getAllTasks() {
return taskRepository.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Task> getTaskById(@PathVariable Long id) {
Optional<Task> task = taskRepository.findById(id);
return task.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PutMapping("/{id}")
public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task updatedTask) {
Optional<Task> existingTask = taskRepository.findById(id);
if (existingTask.isPresent()) {
Task task = existingTask.get();
task.setTitle(updatedTask.getTitle());
task.setDescription(updatedTask.getDescription());
return new ResponseEntity<>(taskRepository.save(task), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
taskRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Create React Components:
Create React components to interact with your Spring Boot backend. For example, a TaskList
component to display tasks:
jsximport React, { useState, useEffect } from `react`;
import axios from `axios`;
const TaskList = () => {
const [tasks, setTasks] = useState([]);
useEffect(() => {
fetchTasks();
}, []);
const fetchTasks = async () => {
try {
const response = await axios.get(`http://localhost:8080/api/tasks`);
setTasks(response.data);
} catch (error) {
console.error(`Error fetching tasks:`, error);
}
};
return (
<div>
<h1>Task List</h1>
<ul>
{tasks.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
</div>
);
};
export default TaskList;
Create Form for Creating Tasks: Create a form component for creating tasks:
jsximport React, { useState } from `react`;
import axios from `axios`;
const TaskForm = () => {
const [newTask, setNewTask] = useState({
title: ``,
description: ``
});
const handleChange = (e) => {
setNewTask({
...newTask,
[e.target.name]: e.target.value
});
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`http://localhost:8080/api/tasks`, newTask);
console.log(`Task created successfully:`, response.data);
// You can update the UI or navigate to another page after creating the task
} catch (error) {
console.error(`Error creating task:`, error);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Title:
<input type="text" name="title" value={newTask.title} onChange={handleChange} />
</label>
<br />
<label>
Description:
<input type="text" name="description" value={newTask.description} onChange={handleChange} />
</label>
<br />
<button type="submit">Create Task</button>
</form>
);
};
export default TaskForm;
Integrate Components in App:
Integrate these components into your main App
component or any other components you have.
jsximport React from `react`;
import TaskList from `./TaskList`;
import TaskForm from `./TaskForm`;
const App = () => {
return (
<div>
<TaskList />
<TaskForm />
</div>
);
};
export default App;
Remember to handle state updates, loading indicators, error handling, and other considerations based on the specific requirements of your application. Also, consider incorporating routing if your application involves multiple pages.