Problem
Hi I am making markdown texteditor and I am working on upload image by blob. It works fine at the first time, but when I paste another picture, blob link doesn't formatted correctly.
It looks like: blob:http://localhost:3000/oi4fr-...blob:http://localhost:3000/b340-1204...
.
Even though I initialize blob, and blobURL variables, this keeps happening. How can I solve this?
code
import markdownLinkExtractor from 'markdown-link-extractor'
import { useRef, useState } from 'react'
import { ReactMarkdown } from 'react-markdown/lib/react-markdown'
export default function Home() {
const [input, setInput] = useState('')
const textArea = useRef(null)
const handlePaste = async(e) => {
if(!e.clipboardData.getData('text')){
let blob = undefined
let blobURL = ''
const object = e.clipboardData.items;
const items = [].slice.call(object).filter((obj)=> {
// Filter the image items only
return obj.type.indexOf('image' || 'image/png') !== -1;})
const item = items[0];
console.log(item)
console.log(item.type)
// Get the blob of image
blob = await item.getAsFile();
blobURL = URL.createObjectURL(blob);
console.log("url", blobURL)
textArea.current.addEventListener('paste', (e)=>{
document.execCommand("insertHTML", false, blobURL)
})
}
}
return (
<>
<textarea
ref={textArea}
name=""
id=""
cols="30"
rows="10"
value={input}
onPaste={(e)=>handlePaste(e)}
onChange={(e)=>setInput(e.target.value)}
/>
<ReactMarkdown children={input}/>
</>
)
}
CodePudding user response:
You create a new paste event listener every time, but you never remove the previous one. So the second time you paste, the previous listener will still insert the previous URL and the new listener will also insert the new URL after it, and so on.
You can use the once
option to create a listener that gets automatically removed after it was called once, by passing { once: true }
as third argument to addEventListener
.