Skip to content

Commit

Permalink
Prevent flush from raising error on detached tag (#2447)
Browse files Browse the repository at this point in the history
* 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 <mateuszburzynski@gmail.com>
  • Loading branch information
mdesantis and Andarist authored Oct 17, 2021
1 parent d7d768e commit f2eda82
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/nasty-gorillas-notice.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@emotion/sheet': patch
---

Fixed an issue with `sheet.flush()` crashing if its style elements were already detached by something else.
12 changes: 12 additions & 0 deletions packages/sheet/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,16 @@ describe('StyleSheet', () => {
sheet.flush()
head.removeChild(otherStyle)
})

it('should not crash when flushing when styles are already detached', () => {
const head = safeQuerySelector('head')

const sheet = new StyleSheet(defaultOptions)

sheet.insert(rule)

head.innerHTML = ''

expect(() => sheet.flush()).not.toThrowError()
})
})
2 changes: 1 addition & 1 deletion packages/sheet/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export class StyleSheet {

flush() {
// $FlowFixMe
this.tags.forEach(tag => tag.parentNode.removeChild(tag))
this.tags.forEach(tag => tag.parentNode && tag.parentNode.removeChild(tag))
this.tags = []
this.ctr = 0
if (process.env.NODE_ENV !== 'production') {
Expand Down

0 comments on commit f2eda82

Please sign in to comment.