Skip to content

Commit

Permalink
Handle race conditions in MarkdownHooks
Browse files Browse the repository at this point in the history
Running asynchronous code inside a `useEffect` causes race conditions.
This is now handled correctly.
  • Loading branch information
remcohaszing committed Mar 5, 2025
1 parent ad7f37f commit ef3986c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,18 @@ export function MarkdownHooks(options) {

useEffect(
function () {
let cancelled = false
const file = createFile(options)
processor.run(processor.parse(file), file, function (error, tree) {
setError(error)
setTree(tree)
if (!cancelled) {
setError(error)
setTree(tree)
}
})

return () => {
cancelled = true
}
},
[
options.children,
Expand Down
21 changes: 21 additions & 0 deletions test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,27 @@ test('MarkdownHooks', async function (t) {
})
assert.equal(container.innerHTML, 'Error: rejected')
})

await t.test('should support `MarkdownHooks` rerenders', async function () {
const pluginA = deferPlugin()
const pluginB = deferPlugin()

const result = render(
<MarkdownHooks children={'a'} rehypePlugins={[pluginA.plugin]} />
)

result.rerender(
<MarkdownHooks children={'b'} rehypePlugins={[pluginB.plugin]} />
)

assert.equal(result.container.innerHTML, '')
pluginB.resolve()
pluginA.resolve()
await waitFor(() => {
assert.notEqual(result.container.innerHTML, '')
})
assert.equal(result.container.innerHTML, '<p>b</p>')
})
})

/**
Expand Down

0 comments on commit ef3986c

Please sign in to comment.