Reputation: 13
I am using Quill as a rich text editor for my Node / Express web app.
Quill API has a method called "on" (https://quilljs.com/docs/api/#on) to fire an event every time the editor selection or text changes.
I am using this method to save the contents of the editor to a MySQL database, using quill.root.innerHTM
to capture the entirety of the content in HTML format.
This works well, but my problem is that this approach fires a POST request to my Express endpoint for every keystroke of the user. I don't want to overwhelm the server and I don't need to save every keystroke variation.
One solution I imagined was to delay the DB query by 3 seconds and fire only one request with the most recent content of the editor.
I tried using setTimeout()
to achieve this like so:
app.post('/editor', (req, res) => {
let post = true;
const id = req.query.id;
const data = req.body.content;
setTimeout(() => {
if (post == true) {
post = false;
db.connection.query('UPDATE my_table SET content = ? WHERE id = ?', [data, id], (error) => {
if (error) {
res.status(500).send("Internal server error")
}
res.status(200).send();
});
}
console.log('data posted');
}, 3000);
});
As you can see, I tried using a boolean. I know why this code doesn't work, but I couldn't figure out a way to "ignore" the requests that happen between the time intervals, and only fire a DB query with the latest data from the editor.
Thanks!
Upvotes: 0
Views: 377
Reputation: 13
I managed to solve the problem using "debounce" from Underscore.js (http://underscorejs.org/#debounce). It works really well!
I did not touch the server route. I implemented it on the frontend. Here's what the code looks like now:
const quill = new Quill('#editor', options);
function update() {
let quillHtml = quill.root.innerHTML;
let quillContent = {
"contents": `${quillHtml}`
};
postData('/editor', id, quillContent);
}
const lazyUpdate = debounce(update, 1000);
quill.on('text-change', lazyUpdate);
postData() is just a helper function to generate a POST request using fetch()
Upvotes: 1