Home > Enterprise >  How to filter city as per selected state in reactjs?
How to filter city as per selected state in reactjs?

Time:03-04

I have data in dropdown now I want to filter city as per selected state, how can I do this in reactJs?

Giving Error:- enter image description here

API Response:- enter image description here

My code:-

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>
  );
}

ThankYou for your efforts!

CodePudding user response:

seems egyptData.Egypt.selectedState is undefine like @Bravo said

you can do it like egyptData.Egypt.selectedState && egyptData.Egypt.selectedState.map() or egyptData?.Egypt?.selectedState?.map()

it seems like it renders before data your set method call (useEffect)

instead of doing this if (!egyptData) return null try if (!egyptData) return <></>

CodePudding user response:

Your setSelectedOption function does not set state to update the UI

For the fix,

You should introduce

const [selectedState, setSelectedState] = useState()

And add it to setSelectedOption

function setSelectedOption(e) {
  console.log(e.target.value);
  let selectedState = e.target.value;
  setSelectedState(selectedState)
}

By the way, egyptData.Egypt.selectedState does not exist in your current code too, you should use egyptData.Egypt[selectedState]

{egyptData.Egypt[selectedState].map((state) => (
   <option>{state}</option>
))}

CodePudding user response:

if you create variable with let it will only access in that block in you're code selectedState only use in setSelectedOption function you have to create state to declare as a global variable

function GetEgyptStates() {
  const [egyptData, setEgyptData] = React.useState(null);
  const [selectedState , setselectedState] = React.useState('');


function setSelectedOption(e) {
  console.log(e.target.value);
 setselectedState(e.target.value)
}


  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={(e)=>setSelectedOption(e)}>
        <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>
  );
}

CodePudding user response:

I think this code can help you **If you want get property with string name you can use 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>
    );
  }

CodePudding user response:

This is working fine now...

Code given below:-

function GetEgyptStates() {
  const [egyptData, setEgyptData] = React.useState(null);
  const [cities, setCities] = React.useState([]);
  const [state, selState] = React.useState();
  function setSelectedOption(e) {
    
    let state = e.target.value;
    setCities(egyptData.Egypt[state]);
  }
  React.useEffect(() => {
    const fetchData = async () => {
      axios
        .get("http://localhost:3000/states-and-districts.json")
        .then((response) => {
          setEgyptData(response.data);
          console.log(response.data);
        });
    };
    fetchData();
  }, []);

  if (!egyptData) return null;

  return (
    <div>
      <select value={state} onChange={setSelectedOption}>
        <option> -- Select State -- </option>
        {Object.entries(egyptData.Egypt).map(([key, val]) => (
          <option>{key}</option>
        ))}
      </select>

      <select>
        <option> -- Select City -- </option>
        {cities.map((city) => (
          <option>{city}</option>
        ))}
      </select>
    </div>
  );
}

Thank you all of you for your support!

  • Related