In my react code I have items as an array in my state.
items[]
I was able to populate items array with few data and need to pass it to my web service. First I need to convert that array to json. This is just crashing for me when I do the Json.stringify.
Is there a different way to do it in react application?
storeDataInDatabase(){
    const myObjStr = JSON.stringify(this.props.items);
    console.log(myObjStr);
}
JSON.stringify(..) will convert your array the right way.
The serialized object would be something like:
{
  "items": [
    {
      "key1": "value1",
      "key2": "value2"
    },
    {
      "key1": "value1",
      "key2": "value2"
    }
  ]
}
But like you wrote in your first sentence, you are setting the items array to state. In think in a way like this:
this.setState({ items })
If so, you have to get the array right from your state in your component:
storeDataInDatabase() {
  const { items } = this.state;
  const myObjStr = JSON.stringify(items);
  console.log(myObjStr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With