0

I am new in the full stack develoment. I have a full stack project with Java Spring boot for the backend and React Typescript for the backend.I have created two entities, Company and Employee.

The entities in the backend:

//For employee:
//domain
   @Data
   public class EmployeeDTO implements Serializable {

    Long id;

    @Size(max = 255)
    String name;

    @Size(max = 255)
    String surName;

    @Size(max = 255)
    String email;

    LocalDate startDate;

    Integer vacationDays;

    Double salary;

    @Size(max = 20)
    String employmentType;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private CompanyDTO employeeCompany;
}

//service
   @Transactional
       public EmployeeDTO save(EmployeeDTO employeeDTO){
           log.debug("Request to save Company : {}",employeeDTO);
           Employee employee = employeeMapper.toEntity(employeeDTO);
           employee = employeeRepository.save(employee);
           return employeeMapper.toDto(employee);
       }

//controller
   @PostMapping("/employee")
       public ResponseEntity<EmployeeDTO> createEmployee(@RequestBody EmployeeDTO employeeDTO){
           log.debug("Rest request to save Company : {}",employeeDTO);
           EmployeeDTO result = employeeService.save(employeeDTO);
           return new ResponseEntity<>(result, HttpStatus.CREATED);
       }


//For the company:

//domain
   @Data
   public class CompanyDTO implements Serializable {
       Long id;

       @NotNull
       @Size(max = 255)
       String name;

       @NotNull
       @Size(max = 255)
       String address;

       @NotNull
       @Size(max = 10, min = 10)
       String phone;
}

//service
   @Transactional
       public CompanyDTO save(CompanyDTO companyDTO){
           log.debug("Request to save Company : {}",companyDTO);
           Company company = companyMapper.toEntity(companyDTO);
           company = companyRepository.save(company);
           return companyMapper.toDto(company);
       }

//controller
   @CrossOrigin
       @PostMapping("/newcompany")
       public ResponseEntity<CompanyDTO> save(@RequestBody CompanyDTO companyDTO){
           log.debug("Rest request to save Company : {}",companyDTO);
           CompanyDTO result = companyService.save(companyDTO);
           return new ResponseEntity<>(result, HttpStatus.CREATED);
       }

Now i will give you for the frontend part with React Typescript:

//For company:
   //model
   export interface CompanyDTO {
     id?: number;
     name?: string;
     address?: string;
     phone?: string;
   }

    //create new company form
   import * as yup from "yup";
   import { useForm } from "react-hook-form";
   import { yupResolver } from "@hookform/resolvers/yup";
   import { useNavigate, useParams } from "react-router-dom";
   import { useEffect, useState } from "react";
   import { Box, Button } from "@mui/material";
   import MuiTextField from "../../components/MuiTextField";
   import axios from "axios";
   import { toast, ToastContainer } from "react-toastify";

    // create schema validation
   export const CompanySchema = yup.object({
     id: yup.string().required("id is required"),
     name: yup.string().required("name is required"),
     address: yup.string().required("address is required"),
     phone: yup.string().required("phone is required"),
   });

   const CompanyForm = () => {
     const params = useParams();
     const navigate = useNavigate();

     useEffect(() => {
       if (params && params?.id) {
         axios
           .get(`http://localhost:8081/api/company/${params?.id}`)
           .then((response) => {
             reset(response.data);
           })
           .catch((error) => console.log(error));
        }
      }, []);

      const {
        handleSubmit,
        reset,
        formState: { errors },
        control,
      } = useForm({
        defaultValues: {
          id: "",
          name: "",
          address: "",
          phone: "",
        },
        resolver: yupResolver(CompanySchema),
      });

      const onSubmit = (data: any) => {
        if (!params?.id) {
          
          fetch("http://localhost:8081/api/newcompany", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
          })
            .then((res) => res.json())
            .then((data) => {
              navigate(`/company/${data?.id}`);
              toast.success("created!");
            });
        } else {
          // update
          fetch(`http://localhost:8081/api/updatecompany/${params?.id}`, {
            method: "PUT" /* or PATCH */,
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
          })
            .then((res) => res.json())
            .then(() => {
              console.log("test");
              toast.info("updated!");
            });
        }
      };

      return (
        <div>
          <Button onClick={() => navigate(-1)} variant="outlined">Back</Button>
          <h1>Company Form</h1>
          <Box
            sx={{
             width: "200px",
            }}
          >
            <form noValidate onSubmit={handleSubmit(onSubmit)}>
              <MuiTextField
                errors={errors}
                control={control}
                name="id"
                label="ID"
              />
             <MuiTextField
                errors={errors}
                control={control}
                name="name"
                label="NAME"
              />
              <MuiTextField
                errors={errors}
                control={control}
                name="address"
                label="ADDRESS"
              />
              <MuiTextField
                 errors={errors}
                 control={control}
                 name="phone"
                 label="PHONE"
             />
             <Button
                type="submit"
                fullWidth
                variant="outlined"
                sx={{ mt: 3, mb: 2 }}
             >
                Submit
             </Button>
            </form>
          </Box>
        </div>
      );
    };

    export default CompanyForm;


    //for the employee:
    //model
    import {CompanyDTO} from "../company/company.model";
    export interface EmployeeDTO {
        id?: number;
        name?: string;
        surName?: string;
        email?: string;
        startDate?: Date;
        vacationDays?: number;
        salary?: number;
        employmentType?: string;
        employeeCompany?: CompanyDTO;

    }

    //create a new employee form
    import * as yup from "yup";
    import { useForm } from "react-hook-form";
    import { yupResolver } from "@hookform/resolvers/yup";
    import { useNavigate, useParams } from "react-router-dom";
    import { useEffect } from "react";
    import { Box, Button } from "@mui/material";
    import MuiTextField from "../../components/MuiTextField";
    import axios from "axios";
    import { toast } from "react-toastify";
    import { CompanySchema } from "../company/CompanyForm";

    // create schema validation
    export const EmployeeSchema = yup.object({
        //id: yup.number().required("id is required"),
        name: yup.string().required("name is required"),
        surName: yup.string().required("surname is required"),
        email: yup.string().required("email is required"),
        startDate: yup.date().required("Start Date is required"),
        vacationDays: yup.number().required("Vacation days are required"),
        salary: yup.number().required("Salary is required"),
        employmentType: yup.string().required("Employment type is required"),
        employeeCompany: CompanySchema.required("Employee Company is required"),
    });

    const EmployeeForm = () => {
       const params = useParams();
       const navigate = useNavigate();

       useEffect(() => {
           if (params && params?.id) {
               axios
                   .get(`http://localhost:8081/api/employee/${params?.id}`)
                   .then((response) => {
                        reset(response.data);
                   })
                    .catch((error) => console.log(error));
            }
        }, []);

       const {
            handleSubmit,
            reset,
            formState: { errors },
            control,
        } = useForm({
            defaultValues: {
                id: "",
                name: "",
                surName: "",
                email: "",
                startDate: "",
                vacationDays: "",
                salary: "",
                employmentType: "",
                employeeCompany: {id: ""},
            },
            resolver: yupResolver(EmployeeSchema),
         });

        const onSubmit = (data: any) => {

            if (!params?.id) {

                //if it is a new record we post it
                fetch("http://localhost:8081/api/employee", {
                    method: "POST",
                    headers: { 'Accept': 'application/json',"Content-Type": "application/json" },
                    body: JSON.stringify(data),
                })
                    .then((response) => response.json())
                    .then((data) => {
                        console.log(data);
                        navigate(`/employee/${data?.id}`);
                        toast.success("created!");
                    });
            } else {
                console.log("updating form data:", data);
                // else we make an update
                fetch(`http://localhost:8081/api/updateemployee/${params?.id}`, {
                    method: "PUT" /* or PATCH */,
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(data),
                })
                    .then((res) => res.json())
                    .then(() => {
                        console.log("test");
                        toast.info("updated!");
                    });
            }
        };

        return (
            <div>
                <Button onClick={() => navigate(-1)} variant="outlined">Back</Button>
                <h1>Employee Form</h1>
                <Box
                    sx={{
                        width: "200px",
                    }}
                >
                    <form noValidate onSubmit={handleSubmit(onSubmit)}>
                         <MuiTextField
                            errors={errors}
                            control={control}
                            name="name"
                            label="NAME"
                         />
                         <MuiTextField
                            errors={errors}
                            control={control}
                            name="surName"
                            label="SURNAME"
                        />
                        <MuiTextField
                            errors={errors}
                            control={control}
                            name="email"
                            label="EMAIL"
                        />
                        <MuiTextField
                            errors={errors}
                            control={control}
                            name="startDate"
                            label="STARTDATE"
                        />
                        <MuiTextField
                            errors={errors}
                            control={control}
                            name="vacationDays"
                            label="VACATION DAYS"
                        />
                        <MuiTextField
                            errors={errors}
                            control={control}
                            name="salary"
                            label="SALARY"
                        />
                        <MuiTextField
                            errors={errors}
                            control={control}
                            name="employmentType"
                            label="EMPLOYMENT TYPE"
                        />
                        <MuiTextField
                            errors={errors}
                            control={control}
                            name="employeeCompany.id"
                            label="Employee Company"
                        />
                        <Button
                            type="submit"
                            
                            fullWidth
                            variant="outlined"
                            sx={{ mt: 3, mb: 2 }}
                        >
                            Submit
                        </Button>
                    </form>
                 </Box>
             </div>
         );
    };

    export default EmployeeForm;

I can submit succesfully a new company record from the company form in React. But the problem is on the employee form. When i'm submitting a new employee it does not do anything. I searched that the cause would be serialize and deserialize the entities. Also, expect dtos i've created and normal entities. Does anyone know what can i do to fix the issue?

1 Answer 1

0

Taking a shot in the dark, as the full set of APIs is not provided. But assuming it is inline with the company URL design, you should change the POST URL to /newemployee instead of /employee in the onSubmit of your EmployeeForm.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.