I have a button that generate powerpoint slides onClick, but the screen is frozen for ~1 seconds during the generation process, here is the flow:
(1). user clicks on the button
(2). turn on the spinner by setIsGenerating(true)
to signal that the generation is in progress
(3). fire async requests to fetch image data in base64 format
(4). used nested loop to insert slides of images and text
(5). writeFile().then(()=> setIsGenerating(false))
is executed to download and stop the spinner. By reading my console log, the freeze starts right before writeFile(),which already returns a promise. Commenting out writeFile() does remove the freeze problem , but this function is mandatory
(6) One more problem is that download started ~1 second after spinner is disappear, but I expect the download to start at the same time as spinner disappear
(7) The downloaded file is ~120,000 KB, which does not seem so large to my eyes , but the performance is bad for some reasons that I don't know
CreatePPT function
const createPPT = async () => {
setIsGenerating(true)
let cart = JSON.parse(localStorage.getItem('cart')) || []
let pres = new pptxgen();
let newCart = JSON.parse(JSON.stringify(cart))
const imgList = []
await Promise.all(newCart.map(async (d) => {
if (d.img !== "") {
let result = await axios.get(d.img, {
responseType: 'arraybuffer'
})
let image = Buffer.from(result.data, 'binary').toString('base64')
image = `data:image/jpg;base64,${image}`
imgList.push(image)
}
}))
newCart.map((d, i) => {
if (d.img !== "") {
d.img = imgList[i]
return d
}
})
newCart.map(d => {
let slide = pres.addSlide()
d.img && slide.addImage({ data: d.img, w: "100%", sizing: { type: "crop" } });
slide.addText(d.title, { x: '0', y: '0', w: '100%', h: '20%', align: 'center', valign: 'middle', color: "ffffff", });
slide.background = { color: "#000000" };
d.content.map(text => {
let slide_2 = pres.addSlide();
d.img && slide_2.addImage({
data: d.img,
w: "100%",
sizing: {
type: "crop"
}
});
slide_2.addText(text, { x: '0', y: '0', w: '100%', h: '20%', align: 'center', valign: 'middle', color: "ffffff", })
slide_2.background = { color: "#000000" };
})
})
//This writeFile() function seems to cause UI to freeze for a short time
pres.writeFile({ fileName: "Sample Presentation.pptx" })
.then(() => {
setIsGenerating(false)
})
}
Button
<Button onClick={createPPT}> Create PPT </Button>