Oliver Darby
Oliver Darby

Reputation: 544

How to display list of camera roll images filenames in react native

Im trying to render a list of images from the users camera roll. I am using expo-media-library to call MediaLibrary.getAssetsAsync() and for a first pass display the list of filenames that I will use as the datasource for the images. Here is my code:

const recentCameraRoll = await MediaLibrary.getAssetsAsync({first: 10});
  const files = recentCameraRoll.assets;
  console.log('Files', Object.values(files.map(file => file.filename)))


  return (
      <View>
        {Object.values(files).map(file => {
        const stringFile = file.filename;
        return (
        <Text key={stringFile}>{stringFile}</Text>
        )
      })}
      </View>
  );

Im getting the error: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.

I have tried using toString and JSON.Stringify but it always comes back with the same error and I cant tell why. My console log comes back with this:

Files Array [
  "IMG_3975.PNG",
  "IMG_3971.PNG",
  "IMG_3914.PNG",
  "IMG_3913.PNG",
  "IMG_3880.PNG",
  "IMG_3879.HEIC",
  "IMG_3873.HEIC",
  "IMG_3870.HEIC",
  "IMG_3869.HEIC",
  "D181FCF1-D7D0-4896-B1EA-C760A6CCBF88.PNG",
]

Which leads me to assume it is an array still but I cant figure it out. If there could be any help on this or also how to render the files coming back as images in general it would be great! Thanks!

Upvotes: 0

Views: 760

Answers (1)

dave
dave

Reputation: 64657

The fact that there is an await in there means you have an async render function - so it is returning a Promise. React can't render a promise. You need to remove the async from your render function, and instead do something like:

const [files, setFiles] = useState([]);
useEffect(() => {
    async function fetchAssets() {
      const recentCameraRoll = await MediaLibrary.getAssetsAsync({first: 10});
      setFiles(recentCameraRoll.assets);
    }
    fetchAssets();
}, []);

console.log('Files', Object.values(files.map(file => file.filename)))

return (
  <View>
    {Object.values(files).map(file => {
      const stringFile = file.filename;
      return (
        <Text key={stringFile}>{stringFile}</Text>
      );
  })}
  </View>
);

Upvotes: 1

Related Questions