2

I have this variable on my component's state:

chartData: {
            labels:null,
            datasets:null
        }

I receive this json from my api to create the chart:

{
"labels": [
    "13/7",
    "14/7",
    "15/7"
],
"datasets": [
    {
        "label": "%%%%",
        "data": [
            0,
            18,
            168
        ],
        "backgroundColor": [
            "rgba(255, 99, 132, 0.6)",
            "rgba(255, 99, 132, 0.6)",
            "rgba(255, 99, 132, 0.6)"
        ]
    }
]

}

The chart appears with no problem but when I try to print the value of this.state.chartData this appears:

TypeError: Converting circular structure to JSON --> starting at object with constructor 'HTMLCanvasElement' | property '__reactInternalInstance$khbtn4bp50s' -> object with constructor 'FiberNode' --- property 'stateNode' closes the circle

Here is the setState of the variable:

this.setState({
        chartData: {

            datasets: response.datasets,
            labels:response.labels
        }
    })

the response is the json above.

UPDATED METHOD JUST TO PRINT VALUES:

 teste=()=>{

    alert("chart data")

    alert(JSON.stringify(this.state.chartData))

}

edit1: print of the console.log(this.state.chartData)

enter image description here

edit 2: api call:

    return fetch(url, {

        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
            labels:params.labels,
            datasets:params.datasets
        })

    }).then(response => response.json())
        .then(json => {
            console.log("fetchJsonFromApi " + JSON.stringify(json))
            // making callback optional
            if (callback && typeof callback === "function") {
                callback(json);
            }
            return json;
        })
        .catch(error => {
            console.log(error)
        });

}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
carlos
  • 63
  • 1
  • 1
  • 4
  • `but when I try to print the value of this.state.chartData` how do you print it? – Vencovsky Jul 17 '19 at 14:14
  • I have created a button just to print the variable, updated the question – carlos Jul 17 '19 at 14:16
  • Why do you need to print it with `JSON.stringify`? Are you reserializing aggregated data? – inetphantom Jul 17 '19 at 14:22
  • use `console.log(...)` or `console.dir(...)` instead of `alert(JSON.stringify(...))`. – Thomas Jul 17 '19 at 14:23
  • The problem is that there is not any circular reference.Updated the question with print of the console.log. I need to seralize because I use that same json as the cody of my request, updated the question with that method too @Thomas – carlos Jul 17 '19 at 14:29
  • @carlos I really don't understand what the problem is – Thomas Jul 17 '19 at 14:37
  • @Thomas the problem is that I am trying to serialize my this.state.chartData variable but i cant because it says that there is a circular reference but there is any circular reference at all – carlos Jul 17 '19 at 14:39

3 Answers3

4

What happens here is that JSON.stringify cannot be used for circular data. Circular data is when you have an object that references some other parent object. If JSON.stringify printed some circular data, it would be a infinity string.

This probably happen because you are getting some circular data from the response.

If you really want to print it and ignore the circular that, you can take a look at this question that have alot of ways to do so.

What I recommend is using console.log instead of alert and in the console you will be able to see circular data with no problem.

Here is a demo for showing circular data, wich is taken from this answer.

// Demo: Circular reference
var o = {};
o.o = o;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(o, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Duplicate reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

var a = {b:1}
var o = {};
o.one = a;
o.two = a;
// one and two point to the same object, but two is discarded:
console.log(JSON.stringify(o))

To remove _meta (wich maybe have circular data) you can do:

if(Array.isArray(response.datasets){
    let newDataSets = response.datasets.map(({label, data, backgroundColor}) => ({label, data, backgroundColor}))
    // do what you want to do
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • there is no circular data on my variable,thats the problem @Vencovsky – carlos Jul 17 '19 at 14:33
  • `TypeError: Converting circular structure to JSON` says the oposite. Inside `response.datasets` you have `_meta`, probably there you have circular data. You say you don't have, but you probably have but you just don't see it. Try removing `_meta` and see what happens. – Vencovsky Jul 17 '19 at 14:40
  • and how do I remove the _meta? Because I didnt put that in there my api only retrieves what is in my question – carlos Jul 17 '19 at 14:43
  • the meta wasnt the problem, the error is still here @Vencovsky – carlos Jul 17 '19 at 14:53
  • @carlos so instead of normal `JSON.stringify`, use the one in the example I showed, it's simple. Why you didn't tried that yet? Please take a look at [this question](https://stackoverflow.com/questions/11616630/how-can-i-print-a-circular-structure-in-a-json-like-format) – Vencovsky Jul 17 '19 at 14:53
-1

If you experience this issue while running your react app locally while using joi-browser npm package. If its work before and it does not work again

I experience the same error when I changed the content of the object variable which I link to my form.

Kindly shutdown the app then start it again

yarn start
npm start
Alabi Temitope
  • 405
  • 5
  • 16
-1

this might help someone, I had the same issue and solved it by commenting the code I put after. The issue happened because the function was called twice.

before:
    afunctionCall()
    return;
    aFunctionCall()
after:
    afunctionCall()
    // return;
    // aFunctionCall()
Greko2015 GuFn
  • 512
  • 6
  • 13