In my NextJS React application, I encountered an issue with circular references when using getInitialProps
to fetch data. Due to the serialization method used by NextJS involving JSON.stringify, it resulted in throwing an error related to circular structure.
To address this problem, I found that utilizing the json-stringify-safe package can be a solution. Here is an example of how it works:
const stringify = require('json-stringify-safe');
const test = { a: 'hello' };
test.b = test;
const testWithoutCircularReferences = JSON.parse(stringify(test));
console.log(testWithoutCircularReferences);
// Output: {"a":"hello","b":"[Circular ~]"}
However, in order to make the object usable within my React app, I need to reverse this process. Despite being a widely-used package, it appears that json-stringify-safe does not offer a built-in parse
function or similar feature to reverse the initial stringify operation. Is there a workaround for achieving this reversal?