Muhammad Raihan Muhaimin Muhammad Raihan Muhaimin - 2 months ago 91
React JSX Question

React-native get all photos from Camera Roll and Camera Roll API

I am trying to get camera roll photos using react native CameraRoll.getPhotos API. The issue I found that the documentation is not great. In react-native official documentation there are two terms that were mentioned

getPhotosReturnChecker
and
getPhotosParamChecker
where I can get the detail about this parameters.

I found the following object that can be passed to
CameraRoll.getPhotos
from bhwgroup blog

{
first: ..., // (required) The number of photos wanted in reverse order of the photo application
after: ..., // A cursor returned from a previous call to 'getPhotos'
groupTypes: ..., // Specifies which group types to filter the results to
// One of ['Album', 'All', 'Event', 'Faces', 'Library', 'PhotoStream', 'SavedPhotos'(default)]
groupName: ..., // Specifies filter on group names, like 'Recent Photos' or custom album titles
assetType: ... // Specifies filter on assetType
// One of ['All', 'Videos', 'Photos'(default)]
}


According to these it always require a parameter first which dictates how many pictures we can get from CameraRoll. Instead if I want all the photos from camera roll how can I get it?

Answer

You'll want to do some paging to access all photos. Basically, you are loading them in chunks, and keeping track of the place where you left off after each fetch. You'll want a state similar to this:

this.state = {
  dataSource: ds.cloneWithRows([]),
  assets: [],
  lastCursor: null,
  noMorePhotos: false,
  loadingMore: false,
};

Then fetching functions similar to these. This example assumes you are using a ListView to display your photos using a ListView.DataSource

tryPhotoLoad() {
  if (!this.state.loadingMore) {
    this.setState({ loadingMore: true }, () => { this.loadPhotos(); });
  }
}

loadPhotos() {
  const fetchParams = {
    first: 35,
    groupTypes: 'SavedPhotos',
    assetType: 'Photos',
  };

  if (Platform.OS === 'android') {
  // not supported in android
    delete fetchParams.groupTypes;
  }

  if (this.state.lastCursor) {
    fetchParams.after = this.state.lastCursor;
  }

  CameraRoll.getPhotos(fetchParams).then((data) => {
    this.appendAssets(data);
  }).catch((e) => {
    console.log(e);
  });
}

appendAssets(data) {
  const assets = data.edges;
  const nextState = {
    loadingMore: false,
  };

  if (!data.page_info.has_next_page) {
    nextState.noMorePhotos = true;
  }

  if (assets.length > 0) {
    nextState.lastCursor = data.page_info.end_cursor;
    nextState.assets = this.state.assets.concat(assets);
    nextState.dataSource = this.state.dataSource.cloneWithRows(
      _.chunk(nextState.assets, 3)
    );
  }

  this.setState(nextState);
}

endReached() {
  if (!this.state.noMorePhotos) {
    this.tryPhotoLoad();
  }
}