Search code examples
reactjspostresponse

Fetch method POST - response data is Promise pending


I have a component which does fetch method='POST' in one of its functions:

handleSubmit(context) {
    let json = {
        username: this.state.username,
        password: this.state.password,
    }
    json = JSON.stringify(json)
    fetch(`/api/auth/token/`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: json,
    })
    .then(response => response.json())
    .then(response => this.loginSuccess(context, response))
}

And this is the loginSuccess function:

loginSuccess(context, response) {
    console.log('Login Success!')
    context.toggleLoginModal()
    context.toggleLoggedIn()
    context.setUsername(response.profile_username)
    context.setUserId(response.profile_id)
}

The problem with this code is, if the response doesn't lie between 200 and 300, like a Bad Request, all the code in loginSuccess will still get executed which shouldn't happen.

So, I have changed

.then(response => response.json())
.then(response => this.loginSuccess(context, response))

to:

.then(response => {
    response.status >= 200 && response.status < 300 ?
            this.loginSuccess(context, response.json())
            :
            console.log(response)
})

Now, in loginSuccess method, the argument response is Promise {<pending>} and response.profile_username is undefined.

How do the solve this?


Solution

  • The Promise has not been fulfilled. Try something like :

    .then(response => {
        response.ok ?
                response.json().then(json => { this.loginSuccess(context, json) })
                :
                console.log(response)
    })