Framework/React Native
[RN][Expo] expo-media-library 앨범 사진 onEndReached로 계속 가져오기
혬수
2023. 8. 1. 18:28
0. 문제
한 page단위로만 Album assets를 받아옴 (대략 20개)
const { assets } = await MediaLibrary.getAssetsAsync();
1. 해결
MediaLibrary.getAssetAsync()로 반환되는 PagedInfo의 endCursor(마지막 asset id)를 이용
→ AssetsOptions를 { after : endCursor }로 하는 MediaLibrary.getAssetAsync( { after : endCursor } ) 실행
→ endCursor부터 한 page 단위 assets 가져와서 기존 앨범 사진 뒤에 추가한다.
FlatList의 onEndReached를 통해 계속 가져와서 기존것에 추가 반복..
* PagedInfo의 hasNextPage는 한 page에 asset이 모두 차 있을때만 true인듯함
2. 코드
import * as MediaLibrary from 'expo-media-library';
const [photos, setPhotos] = useState([])
const [chosenPhoto, setChosenPhoto] = useState(null)
//endCursor담는 ref
const albumRef = useRef(null)
useEffect(() => {
getPhotos();
}, [])
const getPhotos = async () => {
let assetsOptions = {};
//onEndReached로 앨범 사진 가져오는 경우
if(albumRef.current){
assetsOptions = { after: albumRef.current };
}
const { assets, endCursor } = await MediaLibrary.getAssetsAsync( assetsOptions );
albumRef.current = endCursor;
setPhotos([...photos, ...assets]);
};
return photos.length !== 0 && (
<RootView viewStyle={styles.container}>
<FlatList
data={photos}
renderItem={renderItem}
keyExtractor={item => item.id}
numColumns={3}
onEndReached={getPhotos}
//onEndReachedThreshold={0.8}
showsVerticalScrollIndicator="false"
/>
</RootView>
)
* 참고
https://docs.expo.dev/versions/latest/sdk/media-library/#pagedinfo
MediaLibrary
A library that provides access to the device's media library.
docs.expo.dev