I'm using an api, and mapping the data to create a grid of drop down options (Material UI select). There should be two values recorded when the value changes.
I've created an object that has all of the fields in it, which changes when the user changes a select. The only issue is that the select field doesn't show what is currently selected, but if you look at the object, it is clearly changing.
How do I get the current value for each select to show?
In the following code, test is meant to replicate the length of the array returned from the API
import * as React from 'react';
import Box from '@mui/material/Box';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Typography from '@mui/material/Typography';
export default function BasicSelect() {
const test='123456';
const getDefaultSelect = () => {
let selectArray=[]
for (let i=0;i<test.length;i++){
selectArray= [...selectArray,{ qty: 1, qtyUri: 'unit', qtyLabel: 'unit' }]
}
return selectArray
}
React.useEffect(() => {
setSelectValues(getDefaultSelect())
}, []);
const [selectValues, setSelectValues] = React.useState([])
const handleSelectChange = (index, eventData) => {
const newValues = [...selectValues]
newValues[index]={...newValues[index], qtyUri: eventData.qtyUri, qtyLabel: eventData.qtyLabel}
setSelectValues(newValues)
}
return (
<Box sx={{ minWidth: 120 }}>
{selectValues.map((selectValue, index) => (
<Select
value={{qtyUri:selectValue.qtyUri, qtyLabel:selectValue.qtyLabel}}
onChange={(eventData) => handleSelectChange(index, eventData.target.value)}
>
<MenuItem value={{qtyUri:'unit', qtyLabel:'Whole'}}>Whole</MenuItem>
<MenuItem value={{qtyUri:'gram', qtyLabel:'g'}}>g</MenuItem>
<MenuItem value={{qtyUri:'ounce', qtyLabel:'Oz'}}>Oz</MenuItem>
</Select>
))}
<Typography>
{JSON.stringify(selectValues,null,2)}
</Typography>
</Box>
);
}