skip to Main Content

I am just getting started with React and having difficulty in passing the value of the selected dropdown value to the backend. Sharing the code below for reference, any help would be highly appreciated.

On trying to select a value from dropdown, the following error is being thrown. My end goal is to pass the selected value to the backend on form submit

Error
 Cannot read properties of undefined (reading ‘value’)

import React, { useState, useEffect } from 'react'
import Select from 'react-dropdown-select';
import axios from 'axios';

function App() {

  const [data, setData] = useState([]);
  const [value, setValue] = useState([]);
  const [message, setMessage] = useState("");

   const handleSubmit = (event) => {
    event.preventDefault();
    alert(value)
    console.log("Selected value:", value);
    axios.post("./getEmployeeData", {
      value,
    }).then((response) => {
      console.log(response);
    }).catch((error) => {
      console.log(error);
    });
  };

  useEffect(() => {
    fetch("/listEmployees")
      .then((response) => response.json())
      .then((employee) => {
        const parsed = JSON.parse(employee.employeeData);
        const employees = Object.entries(parsed).map(([key, value]) => ({
          label: value,
          value: value
        }));

        setData(employees);
        console.log(parsed, employees);
      });
  }, []);

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <Select
          name="select"
          options={data}
          multi
          onChange={(option) => setValue(option.target.value)
        }
        />;

        <button type="submit"></button>
        <div className="message">{message ? <p>{message}</p> : null}</div>
      </form>
    </div>
  )
}

export default App;

2

Answers


  1. there are a couple of corrections and improvements needed to ensure that the react-dropdown-select component works correctly and that the selected values are handled properly. Here’s an updated version of your code with the necessary adjustments:

        import React, { useState, useEffect } from 'react';
    import Select from 'react-dropdown-select';
    import axios from 'axios';
    
    function App() {
      const [data, setData] = useState([]);
      const [value, setValue] = useState([]);
      const [message, setMessage] = useState("");
    
      const handleSubmit = (event) => {
        event.preventDefault();
        console.log("Selected value:", value);
        axios.post("/getEmployeeData", { value })
          .then((response) => {
            console.log(response);
            setMessage("Data successfully retrieved.");
          }).catch((error) => {
            console.log(error);
            setMessage("Error fetching data.");
          });
      };
    
      useEffect(() => {
        fetch("/listEmployees")
          .then((response) => response.json())
          .then((employee) => {
            const parsed = JSON.parse(employee.employeeData);
            const employees = Object.entries(parsed).map(([key, value]) => ({
              label: value,
              value: key // Assuming 'key' is the unique identifier for employees
            }));
    
            setData(employees);
            console.log(parsed, employees);
          });
      }, []);
    
      return (
        <div>
          <form onSubmit={handleSubmit}>
            <Select
              name="select"
              options={data}
              multi
              onChange={(selected) => setValue(selected.map((item) => item.value))}
            />
            <button type="submit">Submit</button>
            <div className="message">{message && <p>{message}</p>}</div>
          </form>
        </div>
      );
    }
    
    export default App;
    

    Make sure to replace "/getEmployeeData" and "/listEmployees" with the actual endpoints in your application. Also, adjust the value assignment in the onChange event based on how your backend expects the selected values to be sent.

    Login or Signup to reply.
  2. There is an error in your code, react-dropdown-select does not use the same event handling as native HTML elements. The onChange handler receives the selected values directly, not an event.
    you can use it like this

    <Select
        name="select"
          options={data}
          multi
          onChange={(values) => setValue(values)
        }
    

    Not the ‘value’ state has a list of value containing value and label you can extract, then send to api

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search