0

so I'm trying to pass a dynamically generated URL to Image's source prop and, due to React Native limitations, I cannot simply pass a variable as the value of that prop because it won't update to load the image after the variable is set.

So I'm trying to follow the advice here to trigger a change to the source prop.

How can I set the value of a prop in useEffect?

Edit: this is what I'm trying, but still not successfully seeing the image

  const [photoUrl, setPhotoUrl] = useState();

  useEffect(() => {
    async function getSetImg() {
      let img = await getImage(job.afterPhoto.uri);
      setPhotoUrl(img);
    }
    if (job) {
      getSetImg;
    }
  }, [job]);
              <Image
                source={{ uri: photoUrl }}
                style={styles.headerImage}
              />
djangodev
  • 363
  • 5
  • 15
  • If you were to set the prop into a useState() then update the state it will trigger a rerender. You can use the useEffect(()=>{setState(url)} , [url]) might do the trick – Colin Hale Jul 11 '22 at 21:53
  • @ColinHale that is what I'm doing, but not seeing the image. `getImage` is indeed returning a string URL – djangodev Jul 11 '22 at 22:30
  • Can you also add your code where you are also rendering the image. Adding the entire component or making a replica on codesandbox would also be helpful – Colin Hale Jul 11 '22 at 22:32

1 Answers1

1

The problem may not be from setting the values with useState/setState.

I have 2 suggestions you can try.

1. Check if Image style is set explicitly

Q) Does the image show when you hardcode the URL directly (without using setState)?

You can try using the Google logo image for uri: https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png

  • NO (Image don't show): Try the below (style)
  • YES (Hardcoded image is shown ok): Try #2 (ATS)

From RN Docs on Image:

Note that for network and data images, you will need to manually specify the dimensions of your image!

If your styles.headerImage does not have height and width explicitly defined, the <Image/> component may not show. You can easily check if your <Image/> component is visible by setting the backgroundColor='red' while developing.

2. Check App Transport Security (ATS) settings

Q) Are you using iOS? Is the uri source in https or http?

If you are fetching image in http, check the ATS settings.

Also from RN Docs on ATS:

App Transport Security is a security feature introduced in iOS 9 that rejects all HTTP requests that are not sent over HTTPS.

Suggested fix from another SO question is to add NSAllowsArbitraryLoads in the info.plist.

Ziwon
  • 589
  • 6
  • 15
  • Thanks @Ziwon, the hardcoded url works (thought I tested that before but guess not). The url is https so it probably comes down to arbitrary loads. I actually got the state value -> prop approach to work, just forgot to call the function in my useEffect like `getSetImg()` – djangodev Jul 13 '22 at 20:04