The update handling doesn’t work as intended in the react application, the button doesn’t revert back to edit button and the fields don’t get updated

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();
        }
    }
}

New contributor

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật