Say I have a request I want to make on a delay, like Google Docs waiting a moment before sending the "save" request, I'd implement it in browser JavaScript by doing something like this:
// Overwrite this global window variable.
window.saveTimeout = false
// Our sample save function.
let save = text => fetch("some arbitrary save request")
// Lightweight scheduler code that runs each time the user
// types something in an input box.
document.querySelector("textarea#autosaveInput").addEventListener("click", event => {
let text = event.target.value
clearInterval(window.saveTimeout) // clear
setTimeout(() => save(text), 5000) // run save after 5 seconds
})
But in React, I've tested a few methods to do this sort of thing without any luck. I've tried:
- Setting state to a fetch promise.
- Setting it to window, but that window element seems to be cleared each re-render. Further, window isn't always defined especially in a framework like NextJS.
- Searching for this, but "overwriting requests" doesn't seem to yield much.
Here's an example React project I'd be implementing along the lines of:
export default function AutosaveInput(props) {
let onChange = event => {
let text = event.target.value
fetch("some arbitrary save request") // calls every change
}
return (
<div>
<input type="text" onChange={handleSave} />
</div>
)
}