0

I am having trouble with useState in React Native. Trying to set an image's local uri to then upload to firebase, but the setImageURI function isn't being called. I have tried console logging and other ways of determining if the block is being reached, and it is.

Code:

const [ imageURI, setImageURI ] = useState('');

    const handleImageUpload = () => {

        ImagePicker.launchImageLibrary(imagePickerOptions, response => {

            if (response.didCancel) {
                console.log('image picker canceled')
            } else if (response.error) {
                console.log('response error: ', response.error)
            } else {
                setImageURI('new uri');
                setTimeout(() => {
                    console.log('new uri: ', imageURI)
                }, 3000)
                // storageRef.putFile(response.uri).then(response => {
                //     console.log('upload successful: ', response.metadata.fullPath)
                //     // handleSubmit();
                // }).catch(error => {
                //     console.log('there has been an error: ', error)
                // })

            }
            // console.log('response: ', response)
        })
    };

Versions:

react-native-cli: 2.0.1
react-native: 0.61.5
node: v14.3.0

I threw a setTimeout() in there just to see if that would log it, but it still isn't having any effect on imageURI state object. Am I missing something with scope here? Or misunderstanding what I am doing?

  • I have marked this as a duplicate because I believe the other post does answer your question in great detail. PLease let me know if it still doesn't solve your problem – Shubham Khatri Jun 01 '20 at 13:15
  • BTW, the problem of update is because of closure so using a setTimeout doesn't work to print the updated state. The updated value is only reflected in next render cycle – Shubham Khatri Jun 01 '20 at 13:16

0 Answers0