I have the following code to retrieve data from mysql. Image is stores as blob in mysql. I have read many questions about how to display blob image in react but not sure if what I am doing is correct.
import mysql from "mysql2/promise";
export default async function handler(req, res) {
const dbconnection = await mysql.createConnection({
host: "localhost",
user: "root",
password: "Helo1925",
database: "freshbake",
});
try {
const query = "SELECT * FROM item";
const values = [];
const [data] = await dbconnection.execute(query, values);
console.log(data);
dbconnection.end();
data.forEach((item) => {
item.item_image = "data:image/webp;base64," + item.item_image;
}
);
res.status(200).json({ products: data });
} catch (error) {
res.status(500).json({ error: error.message });
}
}
Following code displays the data. Image does not display.
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Item from "./item";
import { useState, useEffect } from "react";
import img from "../public/images/White700.webp";
export default function Catalog() {
const [items, setItems] = useState([]);
useEffect(() => {
async function getItems() {
const apiUrlEndpoint = "http://localhost:3000/api/getitems";
const response = await fetch(apiUrlEndpoint);
const res = await response.json();
console.log(res.products);
setItems(res.products);
}
getItems();
}, []);
return (
<Container
className="container"
fluid
style={{
width: "100%",
height: "100%",
}}>
<Row>
{items.map((item) => (
<Item title={item.item_name} price={item.item_price} image={item.item_image} />
))}
</Row>
</Container>
);
}
I have tried using directly linking an image (not using image from mysql) and it works correctly.
the problem as far as I can see is how you are trying to create the image string using this:
data.forEach((item) => {
item.item_image = "data:image/webp;base64," + item.item_image;
}
your data image looks like is adding all images under one, I will just let the data as it is and do this:
{items.map((item) => (
<Item title={item.item_name} price={item.item_price} image={`data:image/webp;base64,${item.item_image}`} />
))}