Skip to content

Commit ddf8628

Browse files
authored
Protect safeStringify from TypeError (#311)
* updated CHANGELOG.md * Protect safeStringify from TypeError, when state vars have types that can not be stringified (like bigint). This in turn protects getCurrentState(), which failed when dealing with such state. Also, updated the tests with a bigint to show the failure/test the fix.
1 parent ca4f8a1 commit ddf8628

File tree

3 files changed

+18
-10
lines changed

3 files changed

+18
-10
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#### 2.3.17 (2022-04-14)
2+
13
#### 2.3.16 (2022-02-15)
24

35
#### 2.3.15 (2022-01-20)

component/advanced/ProductsList.jsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ class AProduct extends React.Component {
77
this.state = {
88
myName: props.name,
99
orderCount: 0,
10+
orderValue: 1234n,
1011
};
1112
}
1213

src/utils.js

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,21 @@
33
*/
44
exports.safeStringify = (obj, indent = 2) => {
55
let cache = [];
6-
const retVal = JSON.stringify(
7-
obj,
8-
(key, value) =>
9-
typeof value === 'object' && value !== null
10-
? cache.includes(value)
11-
? undefined // Duplicate reference found, discard key
12-
: cache.push(value) && value // Store value in our collection
13-
: value,
14-
indent
15-
);
6+
let retVal = '';
7+
try {
8+
retVal = JSON.stringify(
9+
obj,
10+
(key, value) =>
11+
typeof value === 'object' && value !== null
12+
? cache.includes(value)
13+
? undefined // Duplicate reference found, discard key
14+
: cache.push(value) && value // Store value in our collection
15+
: value,
16+
indent
17+
);
18+
} catch (err) {
19+
retVal = 'State can not be Stringified';
20+
}
1621
cache = null;
1722
return retVal;
1823
};

0 commit comments

Comments
 (0)