Skip to content

Fix recursion with react elements #883

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions src/formatter/sortObject.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@ function safeSortObject(value: any, seen: WeakSet<any>): any {
return value;
}

// return date, regexp and react element values as is
if (
value instanceof Date ||
value instanceof RegExp ||
React.isValidElement(value)
) {
// return date and regexp values as is
if (value instanceof Date || value instanceof RegExp) {
return value;
}

// return react element as is but remove _owner key because it can lead to recursion
if (React.isValidElement(value)) {
const copyObj = { ...value };
delete copyObj._owner;
return copyObj;
}

seen.add(value);

// make a copy of array with each item passed through the sorting algorithm
Expand All @@ -27,9 +30,6 @@ function safeSortObject(value: any, seen: WeakSet<any>): any {
return Object.keys(value)
.sort()
.reduce((result, key) => {
if (key === '_owner') {
return result;
}
if (key === 'current' || seen.has(value[key])) {
// eslint-disable-next-line no-param-reassign
result[key] = '[Circular]';
Expand Down
21 changes: 21 additions & 0 deletions src/formatter/sortObject.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* @flow */

import React from 'react';
import sortObject from './sortObject';

describe('sortObject', () => {
Expand Down Expand Up @@ -42,4 +43,24 @@ describe('sortObject', () => {
c: date,
});
});

it('should remove _owner key from react elements', () => {
const fixture = {
_owner: "_owner that doesn't belong to react element",
component: <div />,
};

expect(JSON.stringify(sortObject(fixture))).toEqual(
JSON.stringify({
_owner: "_owner that doesn't belong to react element",
component: {
$$typeof: Symbol('react.transitional.element'),
type: 'div',
key: null,
props: {},
_store: {},
},
})
);
});
});