I'm stuck with this issue for a few days now.
I made a React native app, that retrieved all restaurant dishes and images from a server. Now my customer wants me to add an offline mode to it.
My idea is to store all data on the phone, in the SQLite database, and use the local database to view all the Data, including all images. Every time the user starts the app it refreshes the data on the phone so it's always updated as well.
But I can't figure out to save the Image as a blob from the web URL.
I know how to convert images to Blob and from Blob to base64 but when I call the function I do not get the correct value back. If I enable the console log and check the result of the function, it prints everything it should.
But when I got the returned value it was garbage or empty, depending on using await and async or not.
This a simple function to turn URL image to blob and then to base64. Console.log is fine but returning does not get me the result.
export const convertImageToBase64 = async (imgUrl) => {
const fr = new FileReader();
await fetch(imgUrl).then((response) => {
response.blob().then((blob) => {
fr.readAsDataURL(blob);
fr.onload = () => {
console.log(fr.result);
};
});
});
};
EDIT: It's not a problem to get the image converted, the problem is to get it back as converted in the return statement so i can put it in the query.
This is the Part in my Code where i need to put in my converted Image.
db.transaction((tx) => {
tx.executeSql(
"CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, img BLOB, done INTEGER)"
);
});
db.transaction(function (tx) {
result.map(async (item) => {
tx.executeSql(
"INSERT INTO items (name,img,done) VALUES (?,?,?)",
[
item.name,
convertImageToBase64(imgUrl), //<-- Something like that
item.done,
]
(tx, results) => {
console.log('Results', results.rowsAffected);
}
);
});
});
Anyone can help with this?
I need a solution to get the converted data to put it in the database.
EDIT: Getting closer.
turned out the problem is the async in my map method. Here i got it as blob or base64, works fine.
`result.map(async (item) => {
console.log(await convertImageToBase64(imgUrl));
//const objectURL = URL.createObjectURL(await convertImageToBase64(config.produktBilderMärkte+item.bild));
})`
But here in my Insert to table method Its noch working. i got empty resultset, and without the async i got null in my img field in the table, where the other values are good.
`result.map(async (item,index) => {
tx.executeSql(
"INSERT INTO markets (name,imgage,done) VALUES (?,?,?)",
[
item.name,
await convertImageToBase64(imgUrl),
item.done,
]
);
});`