skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. You need to sent an array of object with the required structure like

    [
      { 
       label: string, 
       value: string 
      },
      ...
    ]
    

    So your code would be

    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((Emp) => { // don't use same data variable again
            const parsed = JSON.parse(Emp.empPartition);
            const employees = Object.entries(parsed).map(([key, value]) => ({
               label: value,
               value: value
            }));
    
            // put the employees data in the state
            setData(employees); // you need to send an array
            console.log(parsed,employees);
          });
      }, []);
    
      return (
        <div>
           <Select
            options={data}
           />
        </div>
      )
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search