Home > Software design >  How do I get the name and id of a dropdown list and append to formdata in React?
How do I get the name and id of a dropdown list and append to formdata in React?

Time:02-27

I have a dropdown of data from API. I want to be able to render the name of the HMO list but append the name and id of the SELECTED item.

const Form = () => {
 
  const [hmo, setHmo] = useState([]);
  const [selectedHmo, setSelectedHmo] = useState("");
  const [file, setFile] = useState(null);

  

 
 

  const getHmo = useCallback(async () => {
    try {
      const fetchHmo = await Axios.post("apiEndpoint/hmo");
      const resultHmo = fetchHmo.data.data;
      setHmo(resultHmo);
    } catch (err) {
      console.log(err);
    }
  }, []);

 
  useEffect(() => {
    getHmo();
  }, [getHmo]);



  const submitForm = (e) => {
    e.preventDefault();


    var enrollData = new FormData();

  const hmoDetails = hmo.find(hmoItem => hmoItem.id === selectedHmo);

enrollData.append("file", file);
enrollData.append("hmo_id", selectedHmo);
enrollData.append("hmo_name", hmoDetails && hmoDetails.name )
  

  

    Axios({
      method: "POST",
      url: "https://jsonplaceholder.typicode.com/posts",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      data: enrollData,
    })
      .then((response) => {
        console.log(response);
 
      })
      .catch(function (error) {
        console.log(error);
       
      });
  };


  return (
    <div className="form-container">
      <Container>
        
      
          <form onSubmit={submitForm}>
            
            <div className="textfield">
              <TextField
                className="box"
                select
                
                name="hmo"
                required
                SelectProps={{
                  native: true,
                }}
                sx={{
                  width: "23ch",
                }}
                value={selectedHmo}
                onChange={(e) => setSelectedHmo(e.target.value)}
              >
                <option>Select HMO</option>
                {hmo?.map((res) => (
                  <option value={res.id} key={res.id}>
                    {res.name}
                  </option>
                ))}
              </TextField>

              <TextField
                className="box"
                required
                name="file"
                accept=".xlsx, .xls, .csv"
                type="file"
                label="Upload File (.csv, xls, xlsx)"
                onChange={(e) => setFile(e.target.files[0])}
               
                sx={{
                  width: "24ch",
                }}
                
              />
              
            </div>

            <div className="btn">
              <Button
                type="submit"
                variant="contained"
                color="success"
              >
                Upload
              </Button>
              </div>
             
            </div>
          </form>
       
      </Container>
    </div>
  );
};

export default Form;

I got confused at the point of appending the formdata fields as I can access the item id by value={res.id} from hmo map but I need to access the name and id. Then, append to form data before submission. I tried using the array.find() but got undefined. I think there's something i'm not doing right.

CodePudding user response:

You don't need to use the function find, you can obtain directly the name and id by binding the prop value of tag option with object res:

<TextField
  className="box"
  select
  name="hmo"
  required
  SelectProps={{
    native: true,
  }}
  sx={{
    width: "23ch",
  }}
  value={selectedHmo}
  onChange={(e) => setSelectedHmo(JSON.parse(e.target.value))}
>
  <option>Select HMO</option>
  {hmo?.map((res) => (
    <option value={JSON.stringify(res)} key={res.id}> // <=== bind the prop value with your object res
      {res.name}
    </option>
  ))}
</TextField>;

Your handler :

const submitForm = (e) => {
  e.preventDefault();

  var enrollData = new FormData();


  enrollData.append("file", file);
  enrollData.append("hmo_id", selectedHmo.id);
  enrollData.append("hmo_name", selectedHmo.name);

  Axios({
    method: "POST",
    url: "https://jsonplaceholder.typicode.com/posts",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    data: enrollData,
  })
    .then((response) => {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
};
  • Related