0

I'm using react native and expo with an image picker. For some reason, my choosefromlibrary function is not setting the state so I can read it and insert the file location for viewing. Location is not necessary, I tried setImageLocation(result.uri) to no avail so I was just trying different things. result.uri prints with console.log, location prints with console.log, but when I console.log(imageSelected) nothing comes back

const [imageSelected, setImageSelected] = useState("");

const chooseFromLibrary = async () => {
    let location = "";

    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    location = result.uri;
    setImageSelected(location);
    console.log(imageSelected);
}
gmacerola
  • 57
  • 1
  • 7
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Brian Thompson Mar 29 '21 at 19:35

1 Answers1

0

Changing the imageSelected state will not be reflected within your call to chooseFromLibrary. That value is fixed at whatever it was during the render where you called the function.

If you want to do something with the location that you set as your state, use location directly inside your function call (or you can use useEffect to do something every time imageSelected changes).

Flagship1442
  • 1,688
  • 2
  • 6
  • 13