Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Data from Fetch Post that returns response data

Tags:

reactjs

fetch

I am using cross fetch in a react app with redux. In my reducer I save some data to the database using cross fetch's post method. My call returns a response with some data I need to assign to state after saving. I'm having trouble parsing the data though. Below is what the response looks like. How can I get the data that is assigned to body_init?

Response
headers
:
Headers {map: {…}}
ok
:
true
status
:
200
statusText
:
"OK"
type
:
"default"
url
:
"http://localhost:3001/api/updateTransactions"
_bodyInit
:
"[{"category":"Dining Out","months":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}},{"category":"Auto","months":

: : :

Here is the full call. My confusion is that the data returned from the api is actually already formated as json (api returns: res.json(items))

export function saveTransactions(transUpdate,year) {

  return function (dispatch) {

    dispatch(requestTransactionsSave(transUpdate))


return fetch('http://localhost:3001/api/updateTransactions',
{
  method: 'post',
  body: JSON.stringify(transUpdate),
  headers:{'Content-Type': 'application/json'}
})
.then(
    response => response,

    error => console.log('An error occurred.', error)
  )
  .then(res =>

    dispatch(completeTransactionsSave(res))

  )

} }

like image 597
mo_maat Avatar asked May 15 '26 18:05

mo_maat


1 Answers

The problem was simply that I was not calling .json on my returned data. Doint the following solved my problem:

return fetch('http://localhost:3001/api/updateTransactions',
{
  method: 'post',
  body: JSON.stringify(transUpdate),
  headers:{'Content-Type': 'application/json'}
})
.then(
    response => response.json(), //ADDED >JSON() HERE

    error => console.log('An error occurred.', error)
  )
  .then(res =>

    dispatch(completeTransactionsSave(res))

  )
} }
like image 124
mo_maat Avatar answered May 18 '26 08:05

mo_maat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!