Estoy usando una API y mapeando los datos para crear una cuadrícula de opciones desplegables (mui select). Debe haber dos valores registrados cuando el valor cambia.
Creé un objeto que tiene todos los campos, que cambia cuando el usuario cambia una selección. El único problema es que el campo de selección no muestra lo que está seleccionado actualmente, pero si observa el objeto, claramente está cambiando.
¿Cómo obtengo el valor actual para que se muestre cada selección?
En el siguiente código, la prueba está destinada a replicar la longitud de la matriz devuelta por la 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> ); }No puede usar el mismo estado para su mapa que crea la selección 6 y el estado para el valor de selección, porque necesita dar un objeto único a su valor de selección. Explico: la mecánica de Select es comparar el valor seleccionado con el valor del elemento seleccionado para mostrar el elemento. Si proporciona una matriz de elementos, dice que la comparación ArrayAllItems y un elemento no es equivalente y crea una advertencia y no muestra nada.
Código de ejemplo:
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"; const secondTest = [ { qtyUri: "gram", qtyLabel: "g" }, { qtyUri: "gram", qtyLabel: "g" }, { qtyUri: "ounce", qtyLabel: "Oz" }, ]; export default function BasicSelect() { const [alls, setAlls] = React.useState([]); React.useEffect(() => { setAlls(getDefaultSelect()); }, []); const test = "123456"; const getDefaultSelect = () => { let selectArray = []; for (let i = 0; i < test.length; i++) { selectArray = [...selectArray, { qty: 1, qtyUri: "gram", qtyLabel: "g" }]; } return selectArray; }; return ( <Box sx={{ minWidth: 120 }}> {alls.map((element, id) => ( <SelectComponent key={id} defaultValue={element} /> ))} </Box> ); } const SelectComponent = ({ defaultValue }) => { const [selectValue, setSelectValue] = React.useState(defaultValue); return ( <Select value={selectValue} onChange={(eventData) => setSelectValue(eventData.target.value)} > {secondTest.map((item) => ( <MenuItem key={item.qtyUri} value={item.qtyLabel}> {item.qtyLabel} </MenuItem> ))} </Select> ); };