react-native-picker-select
react-native-picker-select copied to clipboard
onValueChange is called multiple times
Describe the bug
Method onValueChange is called multiple times when I dynamically change items of select
To Reproduce
Steps to reproduce the behavior:
const items_1 = [ { label: 'one', value: 1, key: 'one', }, { label: 'two', value: 2, key: 'two', }, ];
const items_2 = [ { label: 'three', value: 3, key: 'three', }, { label: 'four', value: 4, key: 'four', }, ];
const [itemValues, setItemValues] = useState(false);
<View
style={{
borderStyle: 'solid',
borderWidth: 1,
borderColor: 'black',
margin: 10,
padding: 10,
}}>
<RNPickerSelect
items={itemValues ? items_1 : items_2}
placeholder={{
label: 'Select value',
value: '',
key: 'select value',
}}
onValueChange={value => console.log('value: ', value)}
/>
</View>
<Button
title="change items"
onPress={() => setItemValues(!itemValues)}
/>
look at logs and change items
Expected behavior
onValueChange should be called only when user interact with picker.
Additional details
- Device: iOS simulator iPhone 12 (and all physical devices, I tested 3 iPhones)
- OS: iOS 14.4
"dependencies": { "react-native-picker-select": "^8.0.0", "react": "17.0.1", "react-native": "0.64.0" },
Last version when it is working correctly is 8.0.2
Duplicate of https://github.com/lawnstarter/react-native-picker-select/issues/112 ?
But there is a difference, in #112 onValueChange is fired when component re-render, in my case onValueChange is fired when I change items prop of select
But there is a difference, in #112 onValueChange is fired when component re-render, in my case onValueChange is fired when I change items prop of select
Can confirm-- this is a problem on my end too, and is a pain in the butt to work around.
I am experiencing this too, and I created an expo snack reproducing it: https://snack.expo.io/@rabraham/reactnativepickerselectcallbackbug
cc @lfkwtz In case you have any time to look into this? 🙏
For me, it is also fired when I press the "Done" button in iOS picker. And that returns a null value which replaces the actual selected value
@akshitrcrm @Johny8811 did you find the solution
Facing the same issue, any solutions found?
This only happens if you use the value prop as it re-renders and fires onChange again.
My hacky solution
.....
const [changeEnabled, setChangeEnabled] = useState(true);
return (
<RNPickerSelect
value={value}
onClose={() => {
setDisable(true);
onClose();
}}
onValueChange={value => {
if (changeEnabled) {
setValue(value);
}
}}
/>