In a NUXT3 multi component application, some elements might not be available instantly with the document.querySelector API. This behaviour has been identified as a resolved issue since 2022 (and that was about nuxt2) and the only way to solve it seems to activate the selector after setTimeout in the mounted event of the component. I experienced the issue in the process of generating an image from a fabricjs canva, which I reference using its css ID. Note that the canvas does exist as a separate variable in Mounted, but I needed to reference canva is an independent method from shared composable.
mounted()
{
this.canvas=new fabric.Canvas('waveCanvas')
this.drawAll()
this.waveChoixStore.$subscribe((mutation, state) => { this.drawAll() })
const waveResultStore=useResultStore()
setTimeout(() => {
if (waveResultStore.id) useWaveSavePhoto()
})
}
export async function useWaveSavePhoto () {
const waveResultStore=useResultStore()
const waveAppStore=useAppStore();
const entryId=waveResultStore.id
var canvas=document.querySelector(("#waveCanvas"))
var photo = canvas.toDataURL('image/png');
const waveSavePhoto = await $fetch(waveAppStore.ajaxUrl + "wavStoreImage",
{
method: 'POST',
body: {
photo: photo,
i: entryId
},
}).catch((error) => {
if (error) {
console.log(error.data);
alert("error generating schema");
}
})
}