Home > other >  Select input form only getting one value
Select input form only getting one value

Time:10-11

Hello guys i have a MERN stack project, in this project user can register, login, and input data through form, this form have(email, companyname, business choice, images).

The problem is im only getting one value from form select Choice Business, example(if i choose only one value it appear, but if i choose more than one none of them appear).

The state data is array and the data type in mongo db is array too. How do you solve this problem ?

This is the code : Form.js

const Form = () => {

    Axios.defaults.withCredentials = true;
  

    const { emailLog, setEmailLog } = useContext(EmailUser);
    const { userData, setUserData } = useContext(UserData);

    const handleSubmit = async (e) => {
      e.preventDefault();

      const formData = new FormData();
      
      formData.append('email', emailLog);
      formData.append('CompanyName', userData.cName);
      formData.append('Address', userData.Address);
      formData.append('Phone', userData.phoneNumber);
      formData.append('PresidentName', userData.presidentName);
      formData.append('ManagerEmail', userData.managerEmail);
      formData.append('ManagerPhone', userData.managerPhone);
      formData.append('PICEmail', userData.picEmail);
      formData.append('PICPhone', userData.picPhone);
      formData.append('EstablishedDate', userData.date);
      formData.append('ChoiceBusiness', userData.mainBusiness);
      formData.append('EmployeeNumber', userData.employeeNumber);
      formData.append('NumberOfCustomer', userData.numberOfCustomer);
      if (userData.myFile.length > 1) {
        for(let i = 0; i < userData.myFile.length; i  ) {
        formData.append('file', userData.myFile[i]);
        }
      } else {
        formData.append('file', userData.myFile);
      }
      console.log(userData.mainBusiness);
      fetch("https://anydomain.com/registration", {
        method: 'POST',
        body: formData,
    })
        .then((res) => setTimeout(() => navigate("/home"), 1000))
        .catch((err) => ("Error occured", err));
    }
   
return (
    <div className='form'>
      <Appbar />
        <h2 style={{textAlign: "center", marginTop : "20px"}}>Supplier Data</h2>
    <form className='formForm' method='POST' encType='multipart/form-data' action='#' onSubmit={handleSubmit}>
    <div>
      <input className='inputForm' type='email' value={emailLog} name='email'  onChange={(e) => {
          setUserData(e.target.value) }} />
      <input className='inputForm' type='text' placeholder='Company Name' name="CompanyName"  value={userData.cName}  onChange={(e) => {
          setUserData({...userData, cName : e.target.value})}}/>
      <input className='inputForm' type='text' placeholder='Address' name="Address"  value={userData.Address} onChange={(e) => {
           setUserData({...userData, Address : e.target.value})}} />
      <input className='inputForm' type='tel' placeholder='Phone Number' name="Phone"  value={userData.phoneNumber} onChange={(e) => {
          setUserData({...userData, phoneNumber : e.target.value})}}  />
      <input className='inputForm' type='text' placeholder='President Director Name' name="PresidentName"  value={userData.presidentName} onChange={(e) => {
          setUserData({...userData, presidentName : e.target.value})}} />
      <input className='inputForm' type='email' placeholder='Manager Email' name="ManagerEmail"  value={userData.managerEmail} onChange={(e) => {
           setUserData({...userData, managerEmail : e.target.value})}}  />
      <input className='inputForm' type='tel'  placeholder='Manager Phone' name="ManagerPhone"  value={userData.managerPhone} onChange={(e) => {
          setUserData({...userData, managerPhone : e.target.value})}} />
      <input className='inputForm' type='email'  placeholder='PIC Email' name="PICEmail"  value={userData.picEmail} onChange={(e) => {
          setUserData({...userData, picEmail : e.target.value})}} />
      <input className='inputForm' type='tel'  placeholder='PIC Phone' name="PICPhone"  value={userData.picPhone} onChange={(e) => {
          setUserData({...userData, picPhone : e.target.value})}} />
      <input className='inputForm' type='date' pattern="\d{4}-\d{2}-\d{2}" placeholder='Date' name="EstablishedDate"  value={userData.date} onChange={(e) => {
         setUserData({...userData, date : e.target.value})}} />
          
        <select multiple className='selectBox1' name='ChoiceBusiness'  onChange={(e) => {
            setUserData({...userData, mainBusiness : e.target.value})}} >
                  <option value="" disabled selected hidden>Choose Main Business...</option>
                  <option value="Software License">Software License</option>
                  <option value="IT Services & Consulting">IT Services & Consulting</option>
                  <option value="IT Outsourcing">IT Outsourcing</option>
                  <option value="Hardware">Hardware</option>
                  <option value="General Trading">General Trading</option>
                  <option value="Others">Others</option>
        </select>

        <FormBootstrap.Select className='selectBox'  name='EmployeeNumber'  onChange={(e) => {
            setUserData({...userData, employeeNumber : e.target.value})}}>
            <option value="" disabled selected hidden>Choose Employee Number...</option>
            <option value="1-50">1-50</option>
            <option value="51-100">51-100</option>
            <option value="101-250">101-250</option>
            <option value="251-500">251-500</option>
            <option value="500 ">500 </option>
        </FormBootstrap.Select>
)}

Context :

export default function UserDataProvider({ children }) {
    const [ userData , setUserData ] = useState({
        cName : "",
        Address : "",
        phoneNumber : "",
        presidentName : "",
        managerEmail : "",
        managerPhone : "",
        picEmail : "",
        picPhone : "",
        date: "",
        mainBusiness : [],
        employeeNumber : "",
        numberOfCustomer : "",
        myFile : [],
      });

  return (
    <UserData.Provider value={{ userData, setUserData }}>
     {children}
    </UserData.Provider>
  );
}

Mongoose model :

const DataSchema = new mongoose.Schema({
    email : {
        type : String
    },
    CompanyName : {
        type : String
    },
    Address : {
        type : String
    },
    PhoneNumber : {
        type : String
    },
    PresidentName : {
        type : String
    },
    ManagerEmail : {
        type : String
    },
    ManagerPhone : {
        type : String
    },
    PICEmail : {
        type : String
    },
    PICPhone : {
        type : String
    },
    EstablishedDate : {
        type : Date
    },
    ChoiceBusiness : {
        type : [[String]]
    },
    EmployeeNumber : {
        type : String
    }
}, {timestamps : true});

backend :

app.post("/registration", upload.array('file', 20), async (req, res) => {

    const reqFiles = [];
    const url = "https://anydomain.com/images/";
    for (var i = 0; i < req.files.length; i  ) {
        reqFiles.push(url   req.files[i].filename);       
    };

  

   
     data = new DataModel({
         email : req.body.email,
         CompanyName : req.body.CompanyName,
         Address : req.body.Address,
         PhoneNumber : req.body.Phone,
         PresidentName : req.body.PresidentName,
         ManagerEmail : req.body.ManagerEmail,
         ManagerPhone : req.body.ManagerPhone,
         PICEmail : req.body.PICEmail,
         PICPhone : req.body.PICPhone,
         EstablishedDate : req.body.EstablishedDate,
         ChoiceBusiness : req.body.ChoiceBusiness,
         EmployeeNumber : req.body.EmployeeNumber,
         NumberOfCustomer : req.body.NumberOfCustomer,
         SKAny : req.body.SKAny,
         SKValid : req.body.SKValid,
         NPWPAny : req.body.NPWPAny,
         NPWPValid : req.body.NPWPValid,
         SIUPAny : req.body.SIUPAny,
         SIUPValid : req.body.SIUPValid,
         TDPAny : req.body.TDPAny,
         TDPValid : req.body.TDPValid,
         DomisiliAny : req.body.DomisiliAny,
         DomisiliValid : req.body.DomisiliValid,
         SPKPAny : req.body.SPKPAny,
         SPKPValid : req.body.SPKPValid,
         AuditAny : req.body.AuditAny,
         AuditValid : req.body.AuditValid,
         TaxAny : req.body.TaxAny,
         TaxValid : req.body.TaxValid,
         BankAny : req.body.BankAny,
         BankValid : req.body.BankValid,
         Attachments : reqFiles
        })

    await data.save();
    res.json(data);
});

CodePudding user response:

It is because you change mainBusiness state with e.target.value. The correct way to add into state array is you have to copy previous state into array first and adding new value after it. You can learn more updating array in state on https://beta.reactjs.org/learn/updating-arrays-in-state

<select multiple className='selectBox1' name='ChoiceBusiness'  
onChange={(e) =>{setUserData(userData => ({
...userData,
mainBusiness: [...userData.mainBusiness, e.target.value]
})
  • Related