0

The attempt to save base64 image by calling setImage and useEffect to reflect the change fails. The base64 image saved to useState needs to be passed using navigation.navigate. Any help would be greatly appreciated.

index.js

function Homes({navigation,route}) {
  const [image, setImage] = useState(null);

  useEffect(() => {
    console.log("useEffect");
    (async () => {
      if (Platform.OS !== 'web') {
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (status !== 'granted') {
          alert('Sorry, we need camera roll permissions to make this work!');
        }
      }
    }); 
  }, [image]);

  const ImagePick= async () => {
    try{
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    console.log(result); //see the result below
    if (!result.cancelled) {
      setImage(result); 
    }    
    console.log(image); //does not change. Still Null.
    // navigation.navigate('User',{image: image})
  }
  catch(error){
    console.log(error);
  };
}
return (
<TouchableOpacity
        onPress={() => {
          ImagePick();
        {image &&  navigation.navigate('User',{image: image})}
        }}
        style={styles.button}>
        <Text style={styles.text}>upload</Text>
      </TouchableOpacity>
);
}

The information of console.log(result); enter image description here

Rebecca L
  • 65
  • 7
  • 1
    `image` is a local `const`. Calling `setImage` can not change it, it can only request that the component be rerendered, so the log statement on the next lines can't show a changed value. In your case, i would recommend you use the `result` variable to do your navigation, as in `navigation.navigate('User', {image: result})`. If you only want to do that when result.cancelled is false, you can put that code inside the if block – Nicholas Tower Dec 12 '21 at 05:42
  • And in your effect: `(async () => { ... })` declares an async function but it is never called. – Thomas Dec 12 '21 at 06:14

0 Answers0