0

When using react-select it demands an array of objects, not of data. https://github.com/JedWatson/react-select/issues/5032 "react-select does not actively support options that are just simple strings."

I have a list of cities, and I need to change that list to an object

[{ label: "city", value: "city" }].
    const [selectData, setSelectData] = useState([{ label: "city", value: "city" }]);

function This iterates over the data and should create an object array. But it doesn't....

const CreateSelectData = () => {
var getSelectDataList = [];
allCities.map(
  (city, index) =>
    (getSelectDataList = [...selectData,{label:city, value: city])
);
setSelectData(getSelectDataList);
};

output

 <Select
        options={selectData}
        className='optioncity'
        value='Select a city'
        onChange={handleCityChange}
      />

I have no idea what I have done wrong, but I have looked at it for hours :-) The Select never loads at all

2
  • Assuming allCities is coming from an API call, please try this as soon as the array is available: setSelectData(allCities.map(city => ({label: city, value: city})));. Commented Mar 23, 2022 at 2:19
  • The Select never loads at all - at what point in the control-flow is CreateSelectData method being invoked? Commented Mar 23, 2022 at 2:24

2 Answers 2

1

map is to transform from the original object into another object, but for your case, you should use forEach instead. And you should expand getSelectDataList which is your new array instead of selectData

const CreateSelectData = () => {
var getSelectDataList = [...selectData]; //initialise with your initial `selectData`
allCities.forEach((city, index) => {
   getSelectDataList = getSelectDataList.push({ id: index, name: city })
});
setSelectData(getSelectDataList);
};

If you want to use map. You can try this way

const CreateSelectData = () => {
   var getSelectDataList = allCities.map((city, index) => ({ id: index, name: city })); //create a new list with your expected value
   setSelectData([...selectData, ...getSelectDataList]);
};
Sign up to request clarification or add additional context in comments.

Comments

0

in your function change

allCities.map((city) =>
    (getSelectDataList = [...selectData, { label: city, value: city }])
);

to

allCities.map((city) =>
    (getSelectDataList = [...getSelectDataList, { label: city, value: city }])
);

1 Comment

a better option might be to use a reduce statement than a map. what you are doing should work but its better to use a reduce.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.