Home > Mobile >  Trying to retrieve localUri from assets in Expo MediaLibrary, why does this return null?
Trying to retrieve localUri from assets in Expo MediaLibrary, why does this return null?

Time:05-28

I have two questions here, an Expo MediaLibrary question, and a linked Javascript/scoping question.

I have a ReactNative Expo app that loads recent images from a users media library. For this I need to use the MediaLibrary.getAssetsAsync() method.

Annoyingly, .getAssetsAsync() does not return localUri needed to display the image. It returns uri property which looks like this: "uri": "ph://8A1262C3-23F7-4BD3-8943-C01128DCEEB1"

Unless I'm mistaken, I can't use an asset file uri like this to display images in react, we need localUri. So for each photo I am calling the MediaLibrary.getAssetInfoAsync() method - which returns localUri. Here's how I am accomplishing that:

   const selectAlbum =  async (albumName) => {       

        const foundAlbum = await MediaLibrary.getAssetsAsync({album: albumName, mediaType: 'photo', first: 20})
        const assets = foundAlbum['assets'] //array of photos or 'assets'
        const assetsWithInfo = []
        
        //for each selected photo 
        for(let i=0; i<assets.length; i  ){
            
             const assetWithInfo = getAssetInfo(assets[i].id)
             //console.log(assetWithInfo) //doesnt work, null etc - WHY?!
             assetsWithInfo.push(assetWithInfo)

        }
    }


  const getAssetInfo = async (id) =>{

        let res = await MediaLibrary.getAssetInfoAsync(id)

        let asset={
            creationTime: res['creationTime'],
            isFavorite: res['isFavorite'],
            localUri: res['localUri'],
        }
        //console.log(asset) //works, object correctly displays 
        return asset
    }

My questions are:

  1. Is there a more efficient way to do this i.e. display images from MediaLibrary without having to call so many functions. This feels messy and more complicated than it should be.

  2. In the getAssetInfo async, the asset object is correctly displayed (using the console.log) with all properties. But when I return this object to the selectAlbum function and console.log the result, I get null etc. Why?

CodePudding user response:

For #2, the issue is you're not awaiting the result of the call.

const assetWithInfo = await getAssetInfo(assets[i].id); should fix it.

  • Related