Jack
Jack

Reputation: 19

TypeError: JSON.stringify cannot serialize cyclic structures. stringify@[native code]

In my react native expo project I am facing an error that says "TypeError: JSON.stringify cannot serialize cyclic structures. stringify@[native code]" Can anyone can help me to fix this problem? i tried using a library called "json-stringify-safe" but after using it like this "body: jsonStringifySafe(MessageData)," it was giving me react-navigation error Can anyone can help me to fix this error?

   const SendMessage = async () => {
        const MessageData = {
            message: currentmessage,
            RoomId: roomid,
            SenderId: mydata._id,
            RecieverId: otheruser[0]._id
        };
        fetch('http://10.0.2.2:3000/saveMessage', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(MessageData),
        })
            .then(res => res.json())
            .then(data => {
                if (data.message === "Message Saved!") {
                    console.log("Message Saved!");
                    setCurrentMessage('');
                } else {
                    alert("Please, Try Again");
                }
            });
    };

My Backend:

router.post("/saveMessage", async (req, res) => {
    const { SenderId, RecieverId, message, RoomId } = req.body;

    try {
        const NewMessage = new Message({
            SenderId,
            RecieverId,
            message,
            RoomId
        })
        await NewMessage.save();
        res.send("Message Saved!")
    }
    catch (err) {
        console.log('error while saving message', err);
        res.status(422).send(err.message);
    }
})

Upvotes: 0

Views: 2417

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

The error is telling you that you have a property on MessageData (or their descendants) that directly or indirectly end up referring to themselves. For instance:

const parent = { children: [] };
const child = { parent };
parent.children.push(child);

At this point, parent refers to child which refers to parent. If you did JSON.stringify on either of them (directly or indirectly), you'd get this error because JSON can't represent cyclical structures:

const parent = { children: [] };
const child = { parent };
parent.children.push(child);
console.log(JSON.stringify(parent));

So you'll have to look at MessageData and the objects it refers to to find out where the cycle is. Note that it could be quite deep down:

const parent = { children: [] };
const child = { parent };
parent.children.push(child);

const zero = {
    one: {
        two: {
            three: {
                parent
            },
        },
    },
};

console.log(JSON.stringify(zero));

Some JavaScript engines offer you more information about the cyclic structure than others. For instance, here's what V8 (the engine used by Chromium browsers and Node.js) says about the above:

js:26 Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property 'children' -> object with constructor 'Array'
    |     index 0 -> object with constructor 'Object'
    --- property 'parent' closes the circle
    at JSON.stringify ()
    at js:26:18

That's quite informative, more so than what you've quoted in your question. So you might try using a Chromium browser if you aren't already to replicate the issue in hopes it can give you more detail about where the cycle is.

Upvotes: 2

Related Questions