Fix stale closure in delayed autosave callback

intermediate
By FrontendAtlas Editorial · Updated Oct 5, 2026
A teammate tried to make autosave "predictable" by capturing the current draft when wiring a delayed callback. That feels reasonable until the user keeps typing: the callback keeps saving the old draft it closed over instead of the latest one. Fix the bug so delayed saves read fresh state at execution time.

Solution idea

export default function createDraftAutosave(initialDraft = ''){

let draft = initialDraft;

Examples
const autosave = createDraftAutosave('hel');
let flush;
autosave.install(cb => { flush = cb; }, value => value);
autosave.setDraft('hello');
flush(); // 'hello'

const autosave = createDraftAutosave('a');
let flush;
autosave.install(cb => { flush = cb; }, value => value);
autosave.setDraft('ab');
flush(); // 'ab'
autosave.setDraft('abc');
flush(); // 'abc'