How to debounce the query results in mention suggestions? #5832
Unanswered
BorisTheTripper
asked this question in
Questions & Help
Replies: 1 comment
-
After working with TipTap's mention functionality, I found a solution that properly handles debounced API calls. Here's how it works: Key Implementation Points
const debouncedFetch = debounce(async (query, callback) => {
try {
const { data } = await axios.get(
'/users?fields[users]=id,email,name&search=%' + query + '%'
)
callback(
data.data.map((item) => ({
id: item.id,
label: `${item.name} (${item.email})`,
}))
)
} catch (error) {
console.error('Error fetching mentions:', error)
callback([])
}
}, 300)
Mention.configure({
HTMLAttributes: {
class: 'mention',
},
suggestion: {
items: ({ query }) => this.fetchSuggestions(query),
allowSpaces: true,
render: suggestion.render,
},
})
async fetchSuggestions(query) {
if (query.length <= 1) {
this.suggestionResults = []
return this.suggestionResults
}
return new Promise((resolve) => {
debouncedFetch(query, (results) => {
this.suggestionResults = results
resolve(this.suggestionResults)
})
})
} The current implementation works reliably, but there's room for improvement in terms of code organization and error handling. I'll update this comment as I make these enhancements. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm looking at the official mention example, and I'm having a hard time imagining how one would implement debouncing in this setup.
The
items()
function insuggestion.js
seems to be called each time the query string changes, and it must always return an array of strings. In the example code this is fine, because a small, hardcoded array is used each time. However, I'm trying to get my items from the server, and I don't want to send a new request each time. Instead, I'd like to only send a new request if it's been over 300ms since the user stopped typing, i.e. I want a debounce.Is it possible to implement debouncing with mention suggestions? Where does it even fit in? I have only found this SO question, but I'm not sure if that's quite the solution I need.
Beta Was this translation helpful? Give feedback.
All reactions