How do i get the status of my response when using fetch in react-native?

15,909

As far as I understand you want to know the http status code of your fetch request.

Usually your response object includes a "status" property. So you should be able to receive the status code by using this:

response.status

In case of a successful request this will return 200.

Share:
15,909
coderzzz18
Author by

coderzzz18

Updated on July 05, 2022

Comments

  • coderzzz18
    coderzzz18 about 2 years

    I am making Log In page for my react native application. My api sends different response when my username and password are valid and invalid. So I want to track and save the status of my response in some state variable and then later perform function accordingly. Please suggest me way to do that.

      doSignUp() {
       console.log("inside post api");
       fetch('MyApiUrl', {
          method: 'POST',
          headers: {
                     'Accept': 'application/json',
                     'Content-Type': 'application/json',
    
                    },
    
    
          body: JSON.stringify({
          password: this.state.password,
          email:this.state.email,
          name: this.state.firstname,
          last_name :this.state.last_name,
          mobile:this.state.mobile,
          ssn:"2222222"
    
         })
          }).then((response) => {console.log('response:',response.status);
                 response.json()}
            .then((responseData) => {
                                    console.log("inside responsejson");
                                    console.log('response object:',responseData)
                                    console.log('refresh token:',responseData[0].token.refresh_token)
                                    console.log('access token:',responseData[0].token.access_token);
    
    
    
             }).done();
    

    }

  • manpenaloza
    manpenaloza almost 8 years
    it seems I edited the answer when you were testing this, the status property is available in the response property of your first .then() callback
  • coderzzz18
    coderzzz18 almost 8 years
    Yes I edited the above code. The problem that now I am getting is the responseData is not in json format , this must be happening due to asynchronous call back code I think, Please suggest me some way to do that. The output that I am recieving on console is ----> inside post api SignUp.js:35 response: 201 SignUp.js:39 inside responsejson SignUp.js:40 response object: undefined ExceptionsManager.js:61 Cannot read property '0' of undefined @manpenaloza
  • coderzzz18
    coderzzz18 almost 8 years
    my goal is to get the status code if it would be success then only I will save access token else I would show msg of invalid username/password. @manpenaloza