Tengo datos en el menú desplegable ahora quiero filtrar la ciudad según el estado seleccionado, ¿cómo puedo hacer esto en reactJs?
Mi código:-
function setSelectedOption(e) { console.log(e.target.value); let selectedState = e.target.value; } function GetEgyptStates() { const [egyptData, setEgyptData] = React.useState(null); React.useEffect(() => { axios .get("http://localhost:3000/states-and-districts.json") .then((response) => { setEgyptData(response.data); console.log(response.data) }); }, []); if (!egyptData) return null; return ( <div> <select onChange={setSelectedOption}> <option> -- Select State -- </option> {Object.entries(egyptData.Egypt).map(([key, val]) => ( <option>{key}</option> ))} </select> <select> <option> -- Select City -- </option> {egyptData.Egypt.selectedState.map((state) => ( <option>{state}</option> ))} </select> </div> ); }
¡Gracias por tus esfuerzos!
Creo que este código puede ayudarlo **Si desea obtener una propiedad con un nombre de cadena, puede usar setEgyptData[selectedState]
function GetEgyptStates() { const [egyptData, setEgyptData] = React.useState(); const [cities,setCities]=React.useState([]); const [selState,setselState]=React.useState([]); const [selcity,setselcity]=React.useState([]); function setSelectedOption(e) { console.log(e.target.value); let selectedState = e.target.value; setselState(selectedState) setCities(setEgyptData[selectedState]) } React.useEffect(() => { const fetchData=async ()=>{ let response =await axios .get("http://localhost:3000/states-and-districts.json"); setEgyptData(response.data); } if(!egyptData) fetchData(); }, [egyptData]); if (!egyptData) return null; return ( <div> <select value={selState} onChange={setSelectedOption}> <option> -- Select State -- </option> {Object.entries(egyptData.Egypt).map(([key, val]) => ( <option key={key}>{key}</option> ))} </select> <select value={selcity} onChange={({target})=>setselcity(target.value)}> <option> -- Select City -- </option> {cities.map((city) => ( <option key={city}>{city}</option> ))} </select> </div> ); }
Su función setSelectedOption
no establece el estado para actualizar la interfaz de usuario
Para la corrección,
deberías presentar
const [selectedState, setSelectedState] = useState()
Y agréguelo a setSelectedOption
function setSelectedOption(e) { console.log(e.target.value); let selectedState = e.target.value; setSelectedState(selectedState) }
Por cierto, egyptData.Egypt.selectedState
tampoco existe en su código actual, debe usar egyptData.Egypt[selectedState]
{egyptData.Egypt[selectedState].map((state) => ( <option>{state}</option> ))}
parece que egyptData.Egypt.selectedState
no está definido como dijo @Bravo
puede hacerlo como egyptData.Egypt.selectedState && egyptData.Egypt.selectedState.map()
o egyptData?.Egypt?.selectedState?.map()
parece que se procesa antes de que los datos llamen a su método establecido (useEffect)
en lugar de hacer esto if (!egyptData) return null
, intente if (!egyptData) return <></>