Home > Enterprise >  React get value from select dropdown populated from API
React get value from select dropdown populated from API

Time:08-21

I have a select component:

<Select}>
            {data &&
              data.map((survey) => (
                <Option key={survey.id} value={survey.id}>
                  {survey.name}
                </Option>
              ))}
          </Select>

The data array is coming from an API fetch using axios, which is then saved in the state data:

const [data, setData] = useState([]);

How do I grab the selected value and display it?

I tried adding an onChange handler to the component and save the e.target.value in a separate piece of state:

onChange={e => setInput(e?.target?.value)}

However, I'm getting an error that value is undefined. I suspect it's because the data hasn't loaded yet.

How do you get the selected value from the options when the options are coming from an API? (i.e., dynamic dropdown)

CodePudding user response:

Try like this :

  const [data, setData] = useState([]);
  const handleChange = (e) => {
    console.log(e.target.value);
    setData(e.target.value);
  };

   <select onChange={handleChange}>
      {dataArr &&
        dataArr.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>

Example : Example

CodePudding user response:

Can you confirm that the value attribute on the option tag is properly set and it has the value you want it to have.

CodePudding user response:

You can use useEffect hook to update select options. Whenever the data is changed (which means loaded in this case), the code inside of useEffect will be re-evaluated. Hence, inside of the useEffect you can reach the data and extract the needed information. Then, set a new state in onChange handler to show the data at somewhere else.

Here is an example:

import React, { useState, useEffect } from 'react';

export default function App() {
  const [data, setData] = useState([]);
  const [APIDataResponse,setAPIDataResponse] = useState([])
  const [selectedData,setSelectedData] = useState()

  useEffect(()=>{ // this is just a simulator for api response, you do not need this useEffect, instead just call your api
    setTimeout(()=> {
      setAPIDataResponse([ 
        { name: 'first Option', id: 1},
        { name: 'Second Option', id:4 }
      ])
    },[2000])
  },[])

  useEffect(()=>{ // this is where you update your options by using your api response
    if(APIDataResponse[0]){
      setData([
        { name: APIDataResponse[0].name, id: APIDataResponse[0].id },
        { name: APIDataResponse[1].name, id: APIDataResponse[1].id },
      ])
      console.log(APIDataResponse[0])
    }
  },[APIDataResponse])

  const handleChange = (e) => { // print the value, and update a new state to show it somewhere in your component
    console.log(e.target.value);
    setSelectedData(e.target.value)
  }
  
  return (<div>
    <select onChange={handleChange}>
      {data &&
        data.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>
    {selectedData ? <div>Selected Value: {selectedData} </div> : ''}
  </div>
  );
}
  • Related