I've built my own API to be able to share my database (and so its data) between my website and my mobile app. As we can't really store a real picture in a database, I store there the local relative paths in both website and app folders. This is what it looks like :
(I'd love to need only one field for both website and app's project structure but that's not today's topic)
This is how I call my data from API :
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const getAlbumsFromApi = async () => {
try {
const response = await fetch('https://mywebsite.com/api/album');
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
useEffect(() => { getAlbumsFromApi(); }, []);
And this is my return code :
<View contentContainerStyle={styles.scrollview}>
<Text style={styles.titre_accueil}>
Communauté
</Text>
{isLoading ? <ActivityIndicator/> : (
<FlatList
style={styles.liste_albums}
data={data}
keyExtractor={({ id_album }, index) => id_album}
renderItem={({ item }) => (
<View style={styles.element_liste_album}>
<Image
style={styles.album}
source={{ uri : item.urlapp }}
/>
<Text style={{ color: 'red' }}> {item.urlapp} </Text>
</View>
)}
/>
)}
</View>
Here, you can see how it results to prove you fetching absolute data from API works well :
The thing is that Text works indeed, so I know I fetch correctly my data, but something tells me React Native Image's source URI thing doesn't understand the data I'm passing into it, as the spaces between text are supposed to be my items from my . When I create an tag with require as source, with this exact data string, it works well and display image but I don't want to bring static string into my tag, it has to come from API.
So I don't know what's going on, something tells me the kind of string passed into the source prop can't be readen by URI. Is that so ? If yes, why and how could I fix it ?
If you've readen until this, thanks a lot, I'm sorry for the awfully long topic that could've been formatted way better if I knew how to. Thanks a lot if you have an idea about what's happening there.
CodePudding user response:
At Core, React Native support 2 types of images:
Local Images: Image needs to be embedded with app at runtime using node's
require([asset_path])
and not work for a dynamic path.Networks Images. Those are images hosted to remote server and you reference them by Universal Resource Identifier (URI) and most time is valid
HTTP
orHTTPS
resource link.
You're trying to pass URI as a remote image which is an invalid (.../assets/images/subfolder/filename.ext) URI.
There are 2 ways you can solve this problem and both work well for Mobile and Web.
Convert images to base64 and save encoded image string in database (Brute-force solution)
Upload images to cloud providers like Amazon AWS or Firebase Storage and save respective public links in the database.