Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In iphone shows error maximum call stack exceeded error while importing country-sate-city ,but working in android , window and mac #184

Open
shahidforsdlc opened this issue Jun 26, 2024 · 6 comments

Comments

@shahidforsdlc
Copy link

shahidforsdlc commented Jun 26, 2024

// LocationSelector.js
import React, { useState, useEffect } from 'react';
import { Select, Form, Input } from 'antd';
import { State, City } from 'country-state-city';

const { Option } = Select;

const LocationSelector = ({ form }) => {
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [selectedState, setSelectedState] = useState(null);

  useEffect(() => {
    const statesData = State.getStatesOfCountry('US');
    setStates(statesData);
  }, []);

  const handleStateChange = (value) => {
    setSelectedState(value);
    const selectedStateObj = states.find(state => state.name === value);
    const citiesData = City.getCitiesOfState('US', selectedStateObj.isoCode);
    setCities(citiesData);
    form.setFieldsValue({ city: null }); // Reset city field
  };

  const validateZipCode = (rule, value) => {
    const zipCodeRegex = /^[0-9]{5}(?:-[0-9]{4})?$/;
    // const zipCodeRegex = /^\d{5}$/;
    if (value && !zipCodeRegex.test(value)) {
      return Promise.reject('Invalid ZIP code! Please enter a 5-digit or 9 digit ZIP code. Example 12345 or 12345-1234');
    }
    return Promise.resolve();
  };

  return (
    <>
     <Form.Item
        label="Country"
        name="country"
        initialValue="USA"
        rules={[{ required: true, message: 'Please select a country!' }]}
      >
        <Select
          placeholder="Select country"
          allowClear
          optionFilterProp="children"
          showSearch
          disabled
        >
          <Option value="USA">United States</Option>
        </Select>
      </Form.Item>
      <Form.Item
        name="state"
        label="State"
        rules={[{ required: true, message: 'Please select a state!' }]}
      >
        <Select
        allowClear
        optionFilterProp="children"
        showSearch
          placeholder="Select a state"
          onChange={handleStateChange}
        >
          {states.map((state) => (
            <Option key={state.name} value={state.name}>
              {state.name}
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        name="city"
        label="City"
        rules={[{ required: true, message: 'Please select a city!' }]}
      >
        <Select
        allowClear
        optionFilterProp="children"
        showSearch
        placeholder="Select a city" disabled={!selectedState}>
          {cities.map((city) => (
            <Option key={city.name} value={city.name}>
              {city.name}
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        name="zipCode"
        label="ZIP Code"
        rules={[
          { required: true, message: 'Please enter a ZIP code!', validateTrigger: ['onSubmit'] },
          { validator: validateZipCode, validateTrigger: ['onSubmit'] },
        ]}
      >
        <Input placeholder="Enter ZIP code" />
      </Form.Item>
    </>
  );
};

export default LocationSelector;

@shahidforsdlc shahidforsdlc changed the title In iphone shows error maximum call stack exceeded error ,but working in android , window and mac In iphone shows error maximum call stack exceeded error while importing country-sate-city ,but working in android , window and mac Jun 26, 2024
@Martin-Fenocchio
Copy link

do you have some info about this bug? I am facing the same problem

@shahidforsdlc
Copy link
Author

shahidforsdlc commented Jul 10, 2024 via email

@terence1990
Copy link

terence1990 commented Sep 7, 2024

Getting this too, so bizzare - deffo what @shahidforsdlc large non-async JSON imports on mobile cause memory issue, will try an async approach and revert back on this issue.

@terence1990
Copy link

terence1990 commented Sep 7, 2024

I fixed it this way with async:

const getCountries = async () => {
  const Country = await import('country-state-city/lib/country');
  const {getAllCountries} = Country.default;
  return getAllCountries().sort((a, b) => a.name.localeCompare(b.name));
};

const getCities = async (country: string, state?: string) => {
  const City = await import('country-state-city/lib/city');
  const {getCitiesOfState, getCitiesOfCountry} = City.default;
  return state ? getCitiesOfState(country, state) : getCitiesOfCountry(country) ?? [];
}

Since it's now async, becomes troublesome as need to run a side affect in react, so used a hook:

import { ICity, ICountry, IState } from 'country-state-city/lib/interface';

export const useCountriesAndCities = (props?: {
  country?: string,
  state?: string
}) => {
  const [countries, setCountries] = useState<ICountry[]>([]);
  const [cities, setCities] = useState<ICity[]>([]);

  useEffect(() => {
    getCountries().then(setCountries);
  }, []);

  useEffect(() => {
    if (props?.country && props?.state) {
      getCities(props.country, props.state).then(setCities);
    }
  }, [props?.country, props?.state]);

  const phoneCodes = useMemo(() => countries
    .map((country) => ({
      value: country.phonecode.startsWith('+')
        ? country.phonecode
        : `+${country.phonecode}`,
      label: `${country.flag} ${
        country.phonecode.startsWith('+')
          ? country.phonecode
          : `+${country.phonecode}`
      }`,
    }))
    .filter((a, i, arr) => arr.findIndex((b) => b.value === a.value) === i), [countries]);

  return {
    countries,
    cities,
    phoneCodes
  };

};

Related:
#173
#123

@modernlabrat
Copy link

modernlabrat commented Oct 25, 2024

This issue still exists. I don't think this package is being managed anymore...

@mzakiullahusman
Copy link

I ran into some major problems in production with this issue. As an Android user, wasnt using any emulators to test on iOS and my web app just blew up for iOS users...took me around 2-4 hours to find the culprit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants