I am trying to display images for each country code that i am using for my API (ALPHA_3 array) in a React component. getFlags() and appendImg() are imported and executed in a component, but it looks like the imgs are broken/non-existent.
I found an API (countryflags.io) that provides png's for each country i use - but it uses alpha2 naming. In order to fetch the countryflags API i that uses ALPHA2, i slice my ALPHA_3 array and for each country code in the array i make a fetch request. Everything is saved to localestorage using the alpha2 code as key and blob as value.
When i try to display the blobs they appear as broken images and i cant figure out what causes this. Also, is there a better way to store blobs or is localestorage just fine?
const ALPHA_3 = [
'CAD',
'HKD',
'ISK',
'PHP',
'DKK',
'HUF',
'CZK',
'AUD',
'RON',
'SEK',
'IDR',
'INR',
'BRL',
'RUB',
'HRK',
'JPY',
'THB',
'CHF',
'SGD',
'PLN',
'BGN',
'TRY',
'CNY',
'NOK',
'NZD',
'ZAR',
'USD',
'MXN',
'ILS',
'GBP',
'KRW',
'MYR',
];
const base_url = 'https://www.countryflags.io';
const opts = { mode: 'no-cors', 'Content-Type': 'image/png' };
const ALPHA_2 = [];
const getFlags = () => {
ALPHA_3.forEach((element) => ALPHA_2.push(element.slice(0, -1)));
ALPHA_2.forEach((element) => {
fetch(base_url + `/${element}/flat/32.png`, opts)
.then((response) => response.blob())
.then((png) =>
localStorage.setItem(`${element}`, URL.createObjectURL(png))
);
});
};
export default getFlags;
export const appendImg = () => {
Object.values(localStorage).forEach((v) => {
let image = document.createElement(`img`);
image.src = v;
document.body.appendChild(image);
});
};