-1

this is the error

the form is not updating in the DB. It is showing this bellow error

const handleAddItem = (event) => {
    event.preventDefault();
    const productName = productNameRef.current.value;
    const price = priceRef.current.value;
    const description = descriptionRef.current.value;
    const quantity = quantityRef.current.value;
    const img = imgRef.current.value;

    // console.log(productName, price, description, quantity, img);

    const url = `http://localhost:5000/item`;
    fetch(url, {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(event)
    })
    .then(res=> res.json())
    .then(result =>{
        console.log(result);
    })

}

Here is the code part the handles the submission of the form. and the form is a basic HTML form. This code shows the above mention error snipit that includes the error. Please need some help to solve this. Thank you..

  • https://stackoverflow.com/questions/11547672/how-to-stringify-event-object – shabs May 08 '22 at 07:47
  • Please provide errors and other information inline as _text_ in the body of the question. Please [edit] this question so the error is in the body of the question. If you have not already, please see the [tour]. –  May 12 '22 at 18:54

1 Answers1

0

As the error notes in your screenshot, you have a circular dependency in the JSON object you are trying to stringify.

If you notice, the event parameter you're receiving in your handleAddItem method is actually an HTML Event (it could be a KeyboardEvent or a MouseClickEvent or a PointerEvent..etc). Events carry a lot of information on them, including information about the element being interacted with. That information about the element can include circular dependencies as element references can ultimately include references back to themselves.

It looks like in your case, since you're working within React, the information provided by React Fiber (react's underlying algorithm) that is stored in the event, on a field called stateNode, includes a circular reference back to itself when you do JSON.stringify(event).

What should you do instead You should avoid trying to stringify an event and instead use local state (via useState or your useRef refs you have like product name..etc) and construct an object instead to send to your API like so:

fetch(url, {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify({
    productName, price, description, quantity, img})
    })

You don't need to send an HTML event to your API; you should work with clean object/json data that contains exactly what you need.

Azarro
  • 1,776
  • 1
  • 4
  • 11