Debug School

rakesh kumar
rakesh kumar

Posted on

How to filter the data dynamically based on country ,state and city in react js

import React, { useState, useEffect } from 'react';

const App = () => {
  const [countries, setCountries] = useState([]);
  const [selectedCountry, setSelectedCountry] = useState('');
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchCountries = async () => {
      try {
        // Perform an API call or database fetch to retrieve the country data
        // Replace 'your_countries_api_endpoint' with the actual endpoint URL
        const response = await fetch('your_countries_api_endpoint');
        const data = await response.json();

        setCountries(data);
      } catch (error) {
        console.error('Error fetching countries:', error);
      }
    };

    fetchCountries();
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        if (selectedCountry) {
          // Perform an API call or database fetch to retrieve the filtered data based on the selectedCountry
          // Replace 'your_filtered_data_api_endpoint' with the actual endpoint URL including the selectedCountry parameter
          const response = await fetch(`your_filtered_data_api_endpoint?country=${selectedCountry}`);
          const data = await response.json();

          setData(data);
        } else {
          // Perform an API call or database fetch to retrieve all data
          // Replace 'your_data_api_endpoint' with the actual endpoint URL
          const response = await fetch('your_data_api_endpoint');
          const data = await response.json();

          setData(data);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [selectedCountry]);

  const handleCountryChange = (event) => {
    setSelectedCountry(event.target.value);
  };

  return (
    <div>
      <h1>Data Filtering</h1>
      <label>
        Country:
        <select value={selectedCountry} onChange={handleCountryChange}>
          <option value="">All Countries</option>
          {countries.map((country) => (
            <option key={country.id} value={country.id}>
              {country.name}
            </option>
          ))}
        </select>
      </label>
      <h2>Filtered Data:</h2>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a dropdown for selecting a country. The country data is fetched from an API endpoint or database and stored in the countries state variable. The selected country is stored in the selectedCountry state variable.

Based on the selected country, the data is fetched either for the selected country or for all countries. The data is stored in the data state variable.

The handleCountryChange function is used to update the selected country when the dropdown value changes.

The rendered output displays the selected country in the dropdown and the filtered or all data based on the selected country.

Another Example

import React, { useState, useEffect } from 'react';

const App = () => {
  const [countries, setCountries] = useState([]);
  const [selectedCountry, setSelectedCountry] = useState('');
  const [states, setStates] = useState([]);
  const [selectedState, setSelectedState] = useState('');
  const [cities, setCities] = useState([]);
  const [selectedCity, setSelectedCity] = useState('');
  const [filteredData, setFilteredData] = useState([]);

  useEffect(() => {
    const fetchCountries = async () => {
      try {
        // Perform an API call or database fetch to retrieve the country data
        // Replace 'your_countries_api_endpoint' with the actual endpoint URL
        const response = await fetch('your_countries_api_endpoint');
        const data = await response.json();

        setCountries(data);
      } catch (error) {
        console.error('Error fetching countries:', error);
      }
    };

    fetchCountries();
  }, []);

  useEffect(() => {
    const fetchStates = async () => {
      if (selectedCountry) {
        try {
          // Perform an API call or database fetch to retrieve the state data for the selected country
          // Replace 'your_states_api_endpoint' with the actual endpoint URL including the selectedCountry parameter
          const response = await fetch(`your_states_api_endpoint?country=${selectedCountry}`);
          const data = await response.json();

          setStates(data);
          setSelectedState('');
        } catch (error) {
          console.error('Error fetching states:', error);
        }
      }
    };

    fetchStates();
  }, [selectedCountry]);

  useEffect(() => {
    const fetchCities = async () => {
      if (selectedState) {
        try {
          // Perform an API call or database fetch to retrieve the city data for the selected state
          // Replace 'your_cities_api_endpoint' with the actual endpoint URL including the selectedState parameter
          const response = await fetch(`your_cities_api_endpoint?state=${selectedState}`);
          const data = await response.json();

          setCities(data);
          setSelectedCity('');
        } catch (error) {
          console.error('Error fetching cities:', error);
        }
      }
    };

    fetchCities();
  }, [selectedState]);

  useEffect(() => {
    const fetchFilteredData = async () => {
      if (selectedCity) {
        try {
          // Perform an API call or database fetch to retrieve the filtered data based on selectedCountry, selectedState, and selectedCity
          // Replace 'your_filtered_data_api_endpoint' with the actual endpoint URL including the selectedCountry, selectedState, and selectedCity parameters
          const response = await fetch(
            `your_filtered_data_api_endpoint?country=${selectedCountry}&state=${selectedState}&city=${selectedCity}`
          );
          const data = await response.json();

          setFilteredData(data);
        } catch (error) {
          console.error('Error fetching filtered data:', error);
        }
      }
    };

    fetchFilteredData();
  }, [selectedCity]);

  const handleCountryChange = (event) => {
    setSelectedCountry(event.target.value);
  };

  const handleStateChange = (event) => {
    setSelectedState(event.target.value);
  };

  const handleCityChange = (event) => {
    setSelectedCity(event.target.value);
  };

  return (
    <div>
      <h1>Data Filtering</h1>
      <label>
        Country:
        <select value={selectedCountry} onChange={handleCountryChange}>
          <option value="">Select Country</option>

{countries.map((country) => (
<option key={country.id} value={country.id}>
{country.name}
</option>
))}
</select>
</label>
<br />
<label>
State:
<select value={selectedState} onChange={handleStateChange}>
<option value="">Select State</option>
{states.map((state) => (
<option key={state.id} value={state.id}>
{state.name}
</option>
))}
</select>
</label>
<br />
<label>
City:
<select value={selectedCity} onChange={handleCityChange}>
<option value="">Select City</option>
{cities.map((city) => (
<option key={city.id} value={city.id}>
{city.name}
</option>
))}
</select>
</label>
<br />
<h2>Filtered Data:</h2>
{filteredData.length > 0 ? (
<ul>
{filteredData.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>No data available.</p>
)}
</div>
);
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)