MARTIN ALBARRACIN MARTIN ALBARRACIN - 2 months ago 20
Javascript Question

Get status and data from request api by fetch in react native

I try extract data and status request from request in react native, when utilize this code

function postUser(FirstName, LastName, Phone, Email, Password) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: Email,
password: Password,
first_name: FirstName,
last_name: LastName,
phone: Phone
})
}
return fetch(URLPostUser, data)
.then(response => response.json())
}


in this result don't had status.

when change the return of function, i try get status, but in this case don't have access to data

function postUser(FirstName, LastName, Phone, Email, Password) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: Email,
password: Password,
first_name: FirstName,
last_name: LastName,
phone: Phone
})
}
return fetch(URLPostUser, data)
}

Answer Source

You can do the following

return fetch(URLPostUser, data)
    .then(response => ({ response, json: response.json()}))

Now the promised object is

{
    response: // the response object
    json: // the parsed JSON
}

Or if you don't want the whole response

return fetch(URLPostUser, data)
    .then(response => ({ status: response.status, json: response.json()}))

The resulting promise is of the object

{
    status: // the response object
    json: // the parsed JSON
}