I am trying to add the URL at the start of data[{"products_picture:"..."}] element so that it will display the picture of the product in the application. I can fetch all the information from the API and display it on the app.
Here is the API response of products:
"data": [
{
"id": "213",
"products_id": "213",
"products_picture": "uploads/p/p/example_1.jpg",
"products_name": "placeholder",
},
{
"id": "123",
"products_id": "123",
"products_picture": "uploads/p/p/example_2.jpg",
"products_name": "placeholder3452",
}
]
Below is my code to fetch without my attempts to add the link to products_picture:
const [products, setProducts] = useState([]);
const requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow",
};
const siteUrl = "https://somewebsite.com/";
useEffect(() => {
const getProducts = () => {
fetch(
"http://apitest.dogusyapimarket.com.tr/api/v2/products",
requestOptions
)
.then((response) => response.json())
.then((result) => {
setProducts(result.data);
})
.catch((error) => console.log("error", error));
};
getProducts();
}, []);
I attempted to call result.data outside of the useEffect, but it didn't work, as it was expected. Inside the useEffect, I tried to access the element using result.data.products_picture and concatenate the siteUrl at the beginning of it. However, it resulted in a log of https://somewebsite.com/undefined.
I can think of two solutions as of now
1.Make a wrapper component on the Image to handle this
const BASE_URL = 'https://www.www.com';
const ImageWithBaseUrl = (imageUri, imageProps) => {
const imageUriWithBase = `${BASE_URL}/${imageUri}`;
return <Image {...{imageProps}} source={{uri: imageUriWithBase}}/>;
};
2.Make a generic function to append baseurl
const BASE_URL = 'https://www.www.com';
const appendBaseUrl = imageUri => {
return `${BASE_URL}/${imageUri}`;
};
// and user it like
for(...){
...
<Image source={{uri: appendBaseUrl(data[i].products_picture)}} {...{imageProps}} />;
}