picker icon indicating copy to clipboard operation
picker copied to clipboard

onvaluechange fired when the component is initialized (android)

Open danielzzz opened this issue 6 years ago • 12 comments

Bug report

Summary

when the component is loaded the picker fires onvaluechange function event if the old and the new values are identical

Environment info

react-native info output:

ystem:
    OS: Linux 4.15 Ubuntu 18.04.4 LTS (Bionic Beaver)
    CPU: (8) x64 Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz
    Memory: 4.23 GB / 15.56 GB
    Shell: 4.4.20 - /bin/bash
  Binaries:
    Node: 13.12.0 - ~/.nvm/versions/node/v13.12.0/bin/node
    Yarn: 1.9.4 - /usr/bin/yarn
    npm: 6.14.4 - ~/.nvm/versions/node/v13.12.0/bin/npm
    Watchman: Not Found
  SDKs:
    Android SDK:
      API Levels: 23, 25, 26, 27, 28, 29
      Build Tools: 23.0.1, 23.0.2, 25.0.1, 25.0.2, 26.0.1, 26.0.2, 26.0.3, 27.0.3, 28.0.3, 29.0.2
      System Images: android-26 | Google APIs Intel x86 Atom_64, android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: Not Found
  Languages:
    Java: 1.8.0_171 - /media/daniel/acerlinux/proyectos/android/Sdk/bin/javac
    Python: 2.7.17 - /usr/bin/python
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.11.0 => 16.11.0 
    react-native: 0.62.1 => 0.62.1 
  npmGlobalPackages:
    *react-native*: Not Found

Library version: ^1.6.5

Steps to reproduce

<Picker
        mode={'dropdown'}
        selectedValue={currentTask.task_status_id}
        style={[ls.picker, {backgroundColor: task.task_status.color_hex}]}
        onValueChange={(itemValue, itemIndex) => {
          console.log('pìcker changed');
          console.log(itemValue);
          console.log(currentStatus);
         return;

        }}>
{content.task_statuses.map((s) => {
          return <Picker.Item label={s.name} value={s.id} key={String(s.id)} />;
        })}
      </Picker>

Describe what you expected to happen:

not firing the event on the render.

also I have noticed that the callback is called twice when selecting any value.

please advice, regards dan

danielzzz avatar Jul 28 '20 23:07 danielzzz

We've got the same issue but not for all devices. Some users in production reported this issue. We could reproduce this with a Huawei P20 Pro but interestingly only if Bitdefender Mobile Security is installed and active! In this case the onValueChange is initially triggered ...

This may help others figuring out and implementing a workaround. I guess that in our case a security app was checking the picker programmatically which led to the onValueChange event.

mppperez avatar Sep 17 '20 17:09 mppperez

I have the same issue, Android only. I have a list of options, but after the first render, a result of an API call will change the selected value. When this happens, the onValueChange is triggered and auto selects the first option.

This bug makes this component unusable :/

samuthekid avatar Sep 29 '20 22:09 samuthekid

Any update on this issue?

ankitsdglobal avatar Oct 25 '20 05:10 ankitsdglobal

We are having the same issue with OnePlus and Huawei devices.

bisialessandro avatar Oct 26 '20 10:10 bisialessandro

Any update on this issue? Happening on Google Pixel 3. The only workaround for the double trigger I've thought of was to check the itemValue against the selectedValue, but I have no solution for the initial render.

onValueChange={(itemValue, itemIndex) => { if (selectedValue !== itemValue) performChange }

ppalumbo17 avatar Nov 26 '20 00:11 ppalumbo17

A bootleg method for not triggering this with @ppalumbo17 's method was to reorder the selection order for each picker I had.

renderItems(role) {
    let data = [];
    data.push(<Picker.Item label={role.label} value={role.val} key={role.key} />);
    this.state.roles.forEach(element => {
      if (role != element.value) {
        // console.log(role, element.value);
        data.push(<Picker.Item label={element.label} value={element.value} key={element.value} />);
      }
    });
    return data;
  }
{item.editpressed &&
            <Picker
              mode='dropdown'
              selectedValue={item.role}
              style={styles.institute_role_dropdown}
              onValueChange={(itemValue, itemIndex) => { if (item.role != itemValue) this.editInstitutes(item.id, itemValue, item.role, itemIndex) }} >
              {this.renderItems(item.role)}
            </Picker>
          }
editInstitutes = (id, role, oldRole, roleIndex) => {
    let tempInstitutes = this.state.institutes;
    tempInstitutes.forEach(element => element.role = element.id == id ? role : element.role);
    this.setState({ institute: tempInstitutes });
  }

SArham avatar Dec 05 '20 10:12 SArham

After upgrading to Expo 40 I'm getting this issue on iOS also.

aaronschubert0 avatar Dec 12 '20 15:12 aaronschubert0

I believe we have the same issue. We are using Formik for form validation so this keeps triggering our validation to run and tell the user that they need to select something.

Interesting note. I can't replicate it on the emulator but in testing on real devices I have come to the conclusion that this bug affects anything running Android 10 or less. Android 11 does not seem to be affected. 🤷

JCameronP avatar May 25 '21 18:05 JCameronP

I got same problem and I temporarily avoid it by ignoring onValueChange for several milliseconds after mounted the component.

function MyComponent() {
    const [initialValues, setInitialValues] = useState({"foo": ""})
    const [loaded, setLoaded] = useState(false)
    useEffect(() => {
        (async () => {
            const data = await GetInitialValue()
            setInitialValues(data)
        })()
        const timeoutID = setTimeout(() => setLoaded(true), 100)
        return () => {clearTimeout(timeoutID)}
    }, [])
    return (
        <Formik enableReinitialize={true} initialValues={initialValues} >
            {(props) => (
                <Form>
                    <Item stackedLabel>
                        <Picker
                            selectedValue={initialValues.expectation}
                            onValueChange={value => {
                                // ignore onValueChange for 100 ms after data loading
                                if (loaded) {
                                    props.handleChange("foo")(value)
                                }
                            }}
                            enabled={loaded}  // operation is not permitted for 100 ms, too.
                        >
                            {Items.map(x => {
                                return (
                                    <Picker.Item label={x.label} value={x.value} key={"item"+x.value}/>
                                )
                            })}
                        </Picker>
                    </Item>
                </Form>
            )}
        </Formik>
    )
}

ledmonster avatar May 29 '21 10:05 ledmonster

I created a wrapper component for above purpose.

import React, {useEffect, useState} from 'react';
import {Picker} from "native-base";

export default function PickerWrapper({children}) {
    const [loaded, setLoaded] = useState(false)
    useEffect(() => {
        const timeoutID = setTimeout(() => setLoaded(true), 100)
        return () => {clearTimeout(timeoutID)}
    }, [])
    let newChildren = children
    if (React.isValidElement(children)) {
        if (children.type === Picker) {
            const onValueChange = value => {
                if (loaded) {
                    children.props.onValueChange(value)
                }
            }
            newChildren = React.cloneElement(children, {enabled: loaded, onValueChange: onValueChange})
        }
    }
    return newChildren
}

You can use it with Picker component

<PickerWrapper>
  <Picker ... />
</PickerWrapper>

ledmonster avatar May 29 '21 12:05 ledmonster

I found the same behaviour with package version 2.4.8. I found the index parameter was -1 when the onValueChange was called on initialisation without user-interaction. [Edit: This is not the case for all device types.]

A fix for this was included in version 2.7.0 and I've verified it is fixed in version 2.7.7 on a Samsung Galaxy A25 running Android 14, One UI 6.1. https://github.com/react-native-picker/picker/pull/545

RavenJock avatar Jun 04 '25 02:06 RavenJock

Fixed in #545 and released in v2.7.0. Thanks for confirming the fix on Android 14 with v2.7.7!

Naturalclar avatar Nov 25 '26 06:11 Naturalclar