I’m currently working on the frontend of a full stack project, I’m using React(I’m a beginner) for it, but on the teams page, when trying to add edit options, the update button doesn’t seem to work, I used springboot as my backend.
this is my JS code:
import React, { useState, useEffect } from "react";
import axios from "axios";
import './TeamDetailsPage.css'; // Import CSS file
const TeamDetailsPage = () => {
const [teamdetails, setTeamDetails] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('http://localhost:8080/api/teamdetails/all')
.then(response => {
setTeamDetails(response.data);
setLoading(false);
})
.catch(error => {
console.error('Error fetching team details:', error);
setError(error);
setLoading(false);
});
}, []);
const handleEditTeam = (teamDetailId) => {
setTeamDetails(prevTeamDetails => (
prevTeamDetails.map(team => (
team.id === teamDetailId ? { ...team, editing: true } : team
))
));
};
const handleUpdateTeam = (teamDetailId, updatedTeamDetails) => {
axios.put(`http://localhost:8080/api/teamdetails/${teamDetailId}/update`, updatedTeamDetails)
.then(response => {
console.log('Team details updated:', response.data); // Log the updated data
setTeamDetails(prevTeamDetails => (
prevTeamDetails.map(team => (
team.id === teamDetailId ? { ...response.data, editing: false } : team
))
));
})
.catch(error => {
console.error('Error updating team details:', error);
});
};
return (
<div className="team-details-container">
<div className="team-topbar">
<h1>Teams</h1>
</div>
{loading ? (
<p>Loading...</p>
) : error ? (
<p>Error: {error.message}</p>
) : (
teamdetails.map(team => (
<div key={team.id} className="team-container">
{team.editing ? (
<div className="edit-form">
{/* Input fields for editing team details */}
<input
type="text"
value={team.teamName}
onChange={(e) => setTeamDetails(prevTeamDetails => (
prevTeamDetails.map(item => (
item.id === team.id ? { ...item, teamName: e.target.value } : item
))
))}
/>
{/* Add similar input fields for manager, players, etc. */}
<input
type="text"
value={team.manager}
onChange={(e) => setTeamDetails(prevTeamDetails => (
prevTeamDetails.map(item => (
item.id === team.id ? { ...item, manager: e.target.value } : item
))
))}
/>
{/* Add input fields for player names and positions */}
</div>
) : (
<>
<h2 className="team-name">{team.teamName}</h2>
<p className="manager">Manager: {team.manager}</p>
{/* Display player details */}
<ul className="players-list">
{team.players.map(player => (
<li key={player.id} className="player">
{player.playerName} - {player.playerPosition}
</li>
))}
</ul>
</>
)}
{team.editing ? (
<div className="edit-controls">
<button className="update-button" onClick={() => handleUpdateTeam(team.id, team)}>Update</button>
</div>
) : (
<div className="button-container">
<button className="edit-button" onClick={() => handleEditTeam(team.id)}>Edit</button>
</div>
)}
</div>
))
)}
</div>
);
};
export default TeamDetailsPage;
I accessed the put req separately through postman and it worked fine, so I believe the problem lies in the frontend mapping.
this is my dto:
package com.footballleague.footballleague.dto;
import com.footballleague.footballleague.entity.Player;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TeamDetailsDto extends Player {
private Long id;
private String teamName;
private String manager;
private List<PlayerDto> players;
}
this is my controller code:
package com.footballleague.footballleague.controller;
import com.footballleague.footballleague.dto.PlayerDto;
import com.footballleague.footballleague.dto.TeamDetailsDto;
import com.footballleague.footballleague.entity.TeamDetails;
import com.footballleague.footballleague.exception.ResourceNotFoundException;
import com.footballleague.footballleague.mapper.TeamDetailsMapper;
import com.footballleague.footballleague.service.TeamDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@AllArgsConstructor
@RequestMapping("/api/teamdetails")
public class TeamDetailsController {
@Autowired
private final TeamDetailsService teamDetailsService;
@PostMapping("/create")
public ResponseEntity<TeamDetailsDto> createTeamDetails(@RequestBody TeamDetailsDto teamDetailsDto) {
TeamDetailsDto createdTeamDetails = teamDetailsService.createTeamDetails(teamDetailsDto);
return new ResponseEntity<>(createdTeamDetails, HttpStatus.CREATED);
}
@PostMapping("/{teamId}/addplayers")
public ResponseEntity<TeamDetailsDto> addPlayersToTeam(@PathVariable("teamId") Long teamId, @RequestBody List<PlayerDto> playerDtoList) {
TeamDetails updatedTeamDetails = teamDetailsService.addPlayersToTeam(teamId, playerDtoList);//line 30
TeamDetailsDto updatedTeamDetailsDto = TeamDetailsMapper.mapToTeamDetailsDto(updatedTeamDetails);
return new ResponseEntity<>(updatedTeamDetailsDto, HttpStatus.OK);
}
@GetMapping("/{teamDetailId}")
public ResponseEntity<TeamDetails> getTeamDetailsById(@PathVariable("teamDetailId") Long teamDetailId) {
TeamDetails teamDetailsDto = teamDetailsService.getTeamDetailsById(teamDetailId);
return ResponseEntity.ok(teamDetailsDto);
}
@GetMapping("/all")
public ResponseEntity<List<TeamDetailsDto>> getAllTeamDetails() {
List<TeamDetailsDto> teamDetailsDtoList = teamDetailsService.getAllTeamDetails();
return ResponseEntity.ok(teamDetailsDtoList);
}
@PutMapping("/{teamDetailId}/update")
public ResponseEntity<TeamDetailsDto> updateTeamDetails(@PathVariable("teamDetailId") Long teamDetailId, @RequestBody TeamDetailsDto updatedTeamDetails) {
TeamDetailsDto teamDetailsDto = teamDetailsService.updateTeamDetails(teamDetailId, updatedTeamDetails);
return ResponseEntity.ok(teamDetailsDto);
}
@DeleteMapping("/{teamDetailId}/delete")
public ResponseEntity<Void> deleteTeamDetails(@PathVariable("teamDetailId") Long teamDetailId) {
teamDetailsService.deleteTeamDetails(teamDetailId);
return ResponseEntity.noContent().build();
}
@GetMapping("/byname/{teamName}")
public ResponseEntity<TeamDetailsDto> getTeamDetailsByName(@PathVariable("teamName") String teamName) {
TeamDetailsDto teamDetailsDto = teamDetailsService.getTeamDetailsByName(teamName);
return ResponseEntity.ok(teamDetailsDto);
}
@PostMapping("/{teamId}/addPlayer/{playerId}")
public ResponseEntity<Void> addPlayerToTeamById(@PathVariable("teamId") Long teamId,@PathVariable("playerId") Long playerId){
try {
teamDetailsService.addPlayerToTeamById(teamId, playerId);
return ResponseEntity.status(HttpStatus.CREATED).build();
} catch (ResourceNotFoundException ex) {
return ResponseEntity.notFound().build();
}
}
}
Prithiv shiv M V is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.