Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

state is not getting updated in react native

$
0
0

I am selecting a date using react-native-community/datetimepicker, and then on onChange function I am saving my selected date in a state

const [changedDate, setChangedDate] = useState<string | null>(null);const onChange = (event: any, selectedDate: any) => {    setShow(Platform.OS === 'ios');    var momentObj = moment(selectedDate, 'DD-MMM-YYYY');    var momentString = momentObj.format('YYYY-MM-DD');    setChangedDate(momentString); // <---- saving date in a state};

then I am opening a modal:

<TouchableOpacity    onPress={() => {        setSelectPickerModalVisible(!selectPickerModalVisible);        console.log('date on modal>>>>', changedDate); // getting date in my console    }}><Text>open modal</Text></TouchableOpacity>

console output:

date on modal>>>> 2021-11-27

You can see here, when I console my state then I am getting the selected date in console.

Then on modal I have a onPress function which has to do some work, below is this function:

onPress on modal

<TouchableOpacity    onPress={openImageUpload.bind(null, 'picker')}><Text>upload</Text></TouchableOpacity>

openImageUpload function

const openImageUpload = useCallback(    (mode: 'picker' | 'camera' = 'picker') => {        console.log('date on function: ', changedDate); //<--- here in console I am getting my state as null        // some work    },    [uploadHandler],);

console output:

date on function: null

I am not able to understand that why my state is getting null after it has been updated


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>