reactjsjsonreact-select

Unable to populate React Select dropdown from Json Object


I am facing an issue with populating react-select dropdown from JSON object, putting the code below for reference. Any help would be highly appreciated.

import React, { useState, useEffect } from 'react'
import Select from 'react-select';
function App() {

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

  useEffect(() => {
    fetch("/listEmployees")
      .then((response) => response.json())
      .then((data) => {
        // put the employees data in the state
        setData(JSON.parse(data.empPartition));
        console.log(JSON.parse(data.empPartition));
      });
  }, []);

  return (
    <div>
       <Select
        options={data}
       />
    </div>
  )
}

export default App;

The JSON Object on the console looks like this

{0: 'John', 1: 'Davis', 2: 'Sherry'}
0: "John"
1: "Davis"
2: "Sherry"

The dropdown shows up on page but doesn't work with the following error props.options.map is not a function TypeError: props.options.map is not a function at buildCategorizedOptions


Solution

  • So, considering your data shape as;

    {0: 'John', 1: 'Davis', 2: 'Sherry'}
    

    And the value options that react-select accepts is

    { label: string, value: string }[]
    

    You'd have to first transform your data to the options object that react-select understand;

    const input = { 0: 'John', 1: 'Davis', 2: 'Sherry' };
    
    const transformed = Object.entries(input).map(([key, value]) => ({
      label: value,
      value: value
    }));
    
    console.log(transformed);

    Then you can set transformed value to your data state and pass it through option props to your Select component.