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?

4
  • you can send entire array and response.json() will work exactly same way. Commented Dec 10, 2017 at 18:25
  • so it will be res.json(dataresults)? @MdAdil Commented Dec 10, 2017 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); }); Commented Dec 10, 2017 at 18:30
  • @adriam just return the array....it's valid JSON, not everything has to be an object. Alternatively, { results: [] } Commented Dec 10, 2017 at 18:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.