'Unable to access state variable declared inside useEffect

I have a react native screen where I am calling an API on useEffect and setting two state variables using hooks, i.e. cityList, filteredCityList. filteredCityList is bind to autocomplete dropdown. On change of this dropdown, a function called filterCity gets called. I am unable to access the cityList inside this function.

Please advise what am I missing here.

import React, {useCallback, useEffect, useState} from 'react';
import {View, StyleSheet} from 'react-native';
import {Button, Card, Portal, Text, Modal, FAB} from 'react-native-paper';
import {AutocompleteDropdown} from 'react-native-autocomplete-dropdown';
import Icon from 'react-native-vector-icons/Feather';
import {getCities} from '../API/api';
import {useFocusEffect} from '@react-navigation/native';
const AddHospital = () => {
  const [selectedCity, setSelectedCity] = useState(null);
  const [cityListFiltered, setCityListFiltered] = useState([]);
  const [cityList, setCityList] = useState([]);
  const [cityDDLoading, setCityDDLoading] = useState(false);
  const [selectedCityError, setSelectedCityError] = useState(false);
  console.log('reloading');
  
  const filterCity = q => {
    console.log(q);
    console.log('City List', cityList);
  };
  const loadCities = async () => {
    setCityDDLoading(true);
    var citiesResponse = await getCities();
    if (citiesResponse.responseData) {
      var cities = citiesResponse.responseData.records.map(item => ({
        id: item.id,
        title: item.cityname,
      }));
      console.log('setting cities', cities);
      setCityList(cities);
      // setCityListFiltered(cities);
      // setCityDDLoading(false);
    } else {
      console.log('Failed to load cities');
    }
  };
  useEffect(() => {
    loadCities();
  }, []);
  return (
    <View>
      <Card style={styles.container}>
        <Card.Title title="Select Hospital"></Card.Title>
        <Card.Content>
          <AutocompleteDropdown
            clearOnFocus={false}
            closeOnBlur={true}
            closeOnSubmit={false}
            onSelectItem={item => {
              item && setSelectedCity(item);
            }}
            dataSet={cityListFiltered}
            debounce={600}
            onChangeText={text => filterCity(text)}
            suggestionsListMaxHeight={120}
            loading={cityDDLoading}
            useFilter={false} // prevent rerender twice
            textInputProps={{
              placeholder: 'Select City',
              autoCorrect: false,
              autoCapitalize: 'none',
              style: {
                // borderRadius: 25,
                backgroundColor: '#f6f6f6',
                color: 'black',
                paddingLeft: 18,
                borderWidth: 1,
                borderColor: selectedCityError ? 'red' : 'gray',
                borderStyle: 'solid',
              },
              placeholderTextColor: 'black',
            }}
            rightButtonsContainerStyle={{
              // borderRadius: 25,
              right: 8,
              height: 30,
              top: 10,
              alignSelfs: 'center',
              backgroundColor: '#f6f6f6',
              // backgroundColor: "#383b42"
            }}
            inputContainerStyle={{
              backgroundColor: 'transparent',
              zIndex: 0,
            }}
            suggestionsListContainerStyle={
              {
                //backgroundColor: "#383b42"
                //color: '#fff'
                // zIndex: 1000
              }
            }
            containerStyle={{
              flexGrow: 1,
              flexShrink: 1,
              marginBottom: 100,
              marginTop: 10,
              zIndex: 0,
            }}
            renderItem={(item, text) => (
              <Text style={{color: 'black', padding: 15}}>{item.title}</Text>
            )}
            ChevronIconComponent={<Icon name="chevron-down" size={24} />}
            ClearIconComponent={<Icon name="x" size={18} />}
            inputHeight={50}
            showChevron={true}
            showClear={true}
            // style={styles.autoComplete}
          />
        </Card.Content>
      </Card>
      <Text>{cityList.length}</Text>
    </View>
  );
};
export default AddHospital;
const styles = StyleSheet.create({
  container: {
    flex: 0,
    margin: 10,
  },
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source