Skip to content

Commit f2eda82

Browse files
mdesantisAndarist
andauthored
Prevent flush from raising error on detached tag (#2447)
* Prevent flush from raising error on detached tag It prevents `flush()` from raising the following error: `TypeError: tag.parentNode is null`. Such error happens when the `tag` that is being flushed had already been detached from its parent node by a third paryy library, which may be application code or a library that handles the page routing—I'm experiencing this issue with [Turbolinks](https://github.com/turbolinks/turbolinks). * add test and changeseet Co-authored-by: Mateusz Burzyński <[email protected]>
1 parent d7d768e commit f2eda82

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

.changeset/nasty-gorillas-notice.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@emotion/sheet': patch
3+
---
4+
5+
Fixed an issue with `sheet.flush()` crashing if its style elements were already detached by something else.

packages/sheet/__tests__/index.js

+12
Original file line numberDiff line numberDiff line change
@@ -181,4 +181,16 @@ describe('StyleSheet', () => {
181181
sheet.flush()
182182
head.removeChild(otherStyle)
183183
})
184+
185+
it('should not crash when flushing when styles are already detached', () => {
186+
const head = safeQuerySelector('head')
187+
188+
const sheet = new StyleSheet(defaultOptions)
189+
190+
sheet.insert(rule)
191+
192+
head.innerHTML = ''
193+
194+
expect(() => sheet.flush()).not.toThrowError()
195+
})
184196
})

packages/sheet/src/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ export class StyleSheet {
155155

156156
flush() {
157157
// $FlowFixMe
158-
this.tags.forEach(tag => tag.parentNode.removeChild(tag))
158+
this.tags.forEach(tag => tag.parentNode && tag.parentNode.removeChild(tag))
159159
this.tags = []
160160
this.ctr = 0
161161
if (process.env.NODE_ENV !== 'production') {

0 commit comments

Comments
 (0)