1

This is similar to what's asked here at POST array of objects to REST API but my answer needs different formatting

So I have an array of Objects called dataresults like

[
  { reviewID: 5, TextComment: 'lol2314'}, 
  { reviewID: 4, TextComment: 'omg:D:D'}
]

I have no clue how to send this, in my Express code I've been sending data through JSON like this

res.json({
  id1: dataresults[0].reviewID,
  text1: dataresults[0].textcomment
});

And in my React Code, I simply just get this data through a response

fetch('/xd', {
  method: 'POST',
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    cid: user.cid
  })
}).then(function(response) {
  return response.json();
}).then(function(body) {
  console.log(body.id1);
  console.log(body.text1);
});

And this has been working, but now that I want to send the entire dataresults array, I have absolutely no clue on how to do this. I've just been modelling that data with res.json but should I even send it through JSON still when it's an entire array? I would need to change response.json() in my react code to something else im guessing if I did that?

adriam
  • 431
  • 3
  • 8
  • 16
  • you can send entire array and response.json() will work exactly same way. – Md Adil Dec 10 '17 at 18:25
  • so it will be res.json(dataresults)? @MdAdil – adriam Dec 10 '17 at 18:26
  • yep. and in your react app you can do like `.then(function(body) { console.log(body[0].reviewID); console.log(body[0].TextComment); });` – Md Adil Dec 10 '17 at 18:30
  • @adriam just return the array....it's valid JSON, not everything has to be an object. Alternatively, `{ results: [] }` – James Dec 10 '17 at 18:30

1 Answers1

1

You just need to send,

res.json([{
  "id1": dataresults[0].reviewID,
  "text1": dataresults[0].textcomment
}]);

form your express server.

and in react side you can access it like,

.then(function(body) {
  body.forEach((data) => {
     console.log(data.id1)
     console.log(data.text1)
  })
});

hope it will help you.

Hemang
  • 85
  • 3
  • 11