Q:

How to get JSON data from fetch (react-native)

I'm writing small app for iPhone using react native. I'm trying to fetch JSON data from a website using fetch. Like in the example:
   function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  }
  throw new Error(response.statusText)
}

function json(response) {
  return response.json()
}

fetch('/users', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
}).then(status)
  .then(json)
  .then(function(json) {
    console.log('request succeeded with json response', json)
  }).catch(function(error) {
    console.log('request failed', error)
  })

Everything works fine but I need to use that data later. When I try to assign it to some variable in json function, I get "Request error" and after that get the data (correctly). What's the best practise to get that data and have it in some variable to use it later?

A:

I did it like this. I displayed the response on console. You can store the response data in your state variable or in local storage as you want.
  doSignUp() {

     console.log("inside post api");
     fetch('your API URL', {
     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) => response.json())
        .then((responseData) => {
                                 console.log("inside responsejson");
                                 console.log('response object:',responseData)

         }).done();
     }

A:

You can create a variable in the component's constructor:
constructor(props) {
    super(props);
    this.state = {
       jsonData: ''
    }
}

Then you update this variable when you needed:
 .then((responseData) => {
    this.setState({
      jsonData: responseData
    });
  })

