Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a little problem with saving my uri of a picture I have chosen in my react native app.

The following code sample is crucial:

const ProfileScreen = props =>{
    const [pickedImage, setPickedImage] = useState(null);

    const [modalVisible, setModalVisible] = useState(false); //State for visible Modal
    const [userBio, setUserBio] = useState('Useless Placeholder'); //State for users text in the bio

    const verifyPermissions = async () => { //ask for permissions on iOS and Android
        const result = await Permissions.askAsync(Permissions.CAMERA_ROLL);
        if (result.status !== 'granted'){
            Alert.alert("Insufficient permissions!", "You need to grant galery permissions to customise your profile picture!", [{text: "Got it."}]);
            return false;
        };
        return true;
    };

    const takeImageHandler = async () => { //function that opens up the camera
        const hasPermission = await verifyPermissions();
        if (!hasPermission){
            return;
        }
        const image = await ImagePicker.launchImageLibraryAsync({
            allowsEditing: true,
            quality: 0.5,
            aspect: [16,16]
        });
        setPickedImage(image.uri);
        console.log("Data raw is: " + image.uri);
        console.log("Data from hook is: " + pickedImage);
    };

    if(userBio.length == 0 && modalVisible == false){
        setUserBio("Useless Placeholder");
    };

As you can see, I have 2 console logs to check my outcome. I want to save the image.uri to my hook I declared at the top of my ProfileScreen. The problem is what I get as an output in my console:

Data raw is: file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540kubaguette%252FPigeonBuddy/ImagePicker/30953995-840b-451e-a505-6082df16b9e3.jpg Data from hook is: null

Why is setPickedImage(image.uri) not working here? Why can I console.log my uri of the chosen picture but not save this uri to my hook and retrieve it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
313 views
Welcome To Ask or Share your Answers For Others

1 Answer

setPickedImage as any method which updates the state is async by nature.

If this is the only issue, you can track the changes with useEffect.

useEffect(() => {
  console.log(pickedImage);
}, [pickedImage]);

You can see the difference here: https://codesandbox.io/s/usestate-async-rnzox?file=/src/App.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...