简体   繁体   中英

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?

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();
     }

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
    });
  })

Firstly, as you know, each request returns a header and a body

When we use fetch a default response that is headers request. If we need to body of request, that's enough response.json()

return fetch(url,{
  method: 'POST',//GET and ...
  headers:{
      Accept: 'application/json',
      'Content-Type': 'application/json',
  },
  body: JSON.stringify({
      elm: "elm" //is fake
  })
 })
 .then((response)=>response.json()) //   <------ this line 
 .then((response)=>{
   return response ;
 });

And if the body of your request is html dom Just use this response.text()

And if you want to return your header no need to do anything, Just add this line .then((response)=>response.json())

In my case, i used a sails.js with passport local but it's very similar to any other node.js framework, to catch these variables I used for signin a function(req,res) where variables where stored in req.body. In your case req.body.name will contain 'Hubot' and req.body.login will contain 'hubot'.Response will be sent using res.send. check the node.js documentation for more details.

Me works like this

This is button

<Button onPress={this._onPressButton} accessibilityLabel="tap!!!" />

This is action

  _onPressButton() {

  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson.movies);
    })
    .catch((error) => {
      console.error(error);
    });

  }

result

[14:30:19] Array [
[14:30:19]   Object {
[14:30:19]     "id": "1",
[14:30:19]     "releaseYear": "1977",
[14:30:19]     "title": "Star Wars",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "2",
[14:30:19]     "releaseYear": "1985",
[14:30:19]     "title": "Back to the Future",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "3",
[14:30:19]     "releaseYear": "1999",
[14:30:19]     "title": "The Matrix",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "4",
[14:30:19]     "releaseYear": "2010",
[14:30:19]     "title": "Inception",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "5",
[14:30:19]     "releaseYear": "2014",
[14:30:19]     "title": "Interstellar",
[14:30:19]   },
[14:30:19] ]
[14:30:19] Array [
[14:30:19]   Object {
[14:30:19]     "id": "1",
[14:30:19]     "releaseYear": "1977",
[14:30:19]     "title": "Star Wars",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "2",
[14:30:19]     "releaseYear": "1985",
[14:30:19]     "title": "Back to the Future",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "3",
[14:30:19]     "releaseYear": "1999",
[14:30:19]     "title": "The Matrix",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "4",
[14:30:19]     "releaseYear": "2010",
[14:30:19]     "title": "Inception",
[14:30:19]   },
[14:30:19]   Object {
[14:30:19]     "id": "5",
[14:30:19]     "releaseYear": "2014",
[14:30:19]     "title": "Interstellar",
[14:30:19]   },
[14:30:19] ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM