Skip to content

Commit ef3986c

Browse files
committed
Handle race conditions in MarkdownHooks
Running asynchronous code inside a `useEffect` causes race conditions. This is now handled correctly.
1 parent ad7f37f commit ef3986c

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

lib/index.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,18 @@ export function MarkdownHooks(options) {
207207

208208
useEffect(
209209
function () {
210+
let cancelled = false
210211
const file = createFile(options)
211212
processor.run(processor.parse(file), file, function (error, tree) {
212-
setError(error)
213-
setTree(tree)
213+
if (!cancelled) {
214+
setError(error)
215+
setTree(tree)
216+
}
214217
})
218+
219+
return () => {
220+
cancelled = true
221+
}
215222
},
216223
[
217224
options.children,

test.jsx

+21
Original file line numberDiff line numberDiff line change
@@ -1165,6 +1165,27 @@ test('MarkdownHooks', async function (t) {
11651165
})
11661166
assert.equal(container.innerHTML, 'Error: rejected')
11671167
})
1168+
1169+
await t.test('should support `MarkdownHooks` rerenders', async function () {
1170+
const pluginA = deferPlugin()
1171+
const pluginB = deferPlugin()
1172+
1173+
const result = render(
1174+
<MarkdownHooks children={'a'} rehypePlugins={[pluginA.plugin]} />
1175+
)
1176+
1177+
result.rerender(
1178+
<MarkdownHooks children={'b'} rehypePlugins={[pluginB.plugin]} />
1179+
)
1180+
1181+
assert.equal(result.container.innerHTML, '')
1182+
pluginB.resolve()
1183+
pluginA.resolve()
1184+
await waitFor(() => {
1185+
assert.notEqual(result.container.innerHTML, '')
1186+
})
1187+
assert.equal(result.container.innerHTML, '<p>b</p>')
1188+
})
11681189
})
11691190

11701191
/**

0 commit comments

Comments
 (0)