ganesh kaspate
ganesh kaspate

Reputation: 2695

React await promise resolve not getting data

I am using async/await in the following function

forgotPassword = async ({ variables }) => {
    console.log(variables)
    const url = `//url constructed`
    console.log(url)
    try {
      const result: any = await fetch(url, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          mode: 'no-cors'
        }
      })

      console.log('result fetched is -->', result)

      return {
        data: {
          login: result.json()
        }
      }
    } catch (err) {
      this.setState({
        error:
          err?.response?.data?.error_description || err.message || strings.genericError
      })
      throw err
    }
  }

So, In the result when I did

result.json()

i am getting response like :

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
Status: "Successful"
Time: "1619013232787"
__proto__: Object

so when I tried doing

const status = result?.Status

then it gave me undefined

How to get the response ? even the promise is fulfilled.

Upvotes: 0

Views: 100

Answers (1)

FireFighter
FireFighter

Reputation: 706

You need to await result.json() since it returns a promise. https://developer.mozilla.org/de/docs/Web/API/Body/json

 try {
      const result: any = await fetch(url, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          mode: 'no-cors'
        }
      })
      const data = await result.json();
      return {data};

Upvotes: 4

Related Questions