1

I have a fetch API call that calls API back end and in return, I will get the response object with status code. What I am trying to do is base on return, I wanted to return the JSON response with status code. so that other part of the javascript can manipulate base on status code. My fetch function is as follow.

I have tried with as follow below, but it returns as a given screenshot. It gives me promise value which I didn't want to get. enter image description here

export const createUser = ( posts ) => {
    const apiRoute= "/api/register";
    return window.fetch(`${apiRoute}`, {
       "headers": headers,
       method: "POST",
       body: JSON.stringify(posts)
    }).then(response => ({
        'status' : response.status,
        'data'   : response.json()
    }))
        .catch(error => console.error('Error: ', error))
        ;

}

I know that it might be the duplicate from this post (Fetch api - getting json body in both then and catch blocks for separate status codes), but I do not want my data to return as a promise. Instead, I wanted to return fully constructed well form JSON data.

Something like this.

{status: 400, data: {id:1,name:Hello World}}

how can i achieve this?

Achilles
  • 411
  • 1
  • 5
  • 27

1 Answers1

4

"It gives me promise value"

That's right, as per the documentation.

You need to resolve that promise before resolving the outer promise.

For example

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

Alternatively, use an async function

export const createUser = async ( posts ) => {
  const apiRoute= "/api/register";
  try {
    const response = await window.fetch(apiRoute, {
      headers,
      method: "POST",
      body: JSON.stringify(posts)
    })
    return {
      status: response.status,
      data: await response.json()
    }
  } catch (error) {
    console.error('Error: ', error)
    throw error
  }
}
Phil
  • 157,677
  • 23
  • 242
  • 245