When opening my component, I want to get Assets from a Media Folder (which works fine) and then passing it through to another component. The Problem is that when first launching the app, the "listOfAssets" state is empty and when refreshing it, it stores all necessary Assets.
How can I achieve that the Assets are getting stored the first time and that I don’t have to refresh it.
Could there be a problem with my async code?
const [listOfAssets, setListOfAssets] = useState([]);
useEffect(() => {
async function getAssets() {
const assets = await MediaLibrary.getAssetsAsync({
album: folderToSort,
includeSmartAlbums: true,
});
assets.assets.map((asset) => {
listOfAssets.push({
id: asset.id,
uri: asset.uri,
height: asset.height,
width: asset.width,
});
});
}
getAssets();
}, []);
return (
<View>
<SlideComponent
imageUri={listOfAssets}
moveImageToGOAlbum={moveImageToGOAlbum}
/>
</View>
);
3
Answers
You should call your setting function
setListOfAssets
rather than doinglistOfAssets.push
. Something likeOr simplify this further without the .map at all since it’s not really adding anything.
Please try to update your useEffect code block like below:
All states in React are immutable you need to put a new value or object each time you try to use restructuring and you need use a set method to invoque a new state and that call a render method to update the view.