11

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?

5 Answers 5

7

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();
     }
Sign up to request clarification or add additional context in comments.

Comments

6

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

2 Comments

in the fetch method, you usually have two thens like this:.then((response) => { response.text(); console.log(response); }) .then((responseText) => { console.log(responseText); }) .catch((error) => { console.warn(error); }) .done(); I was wondering what does each of the two then returns and why is it organized that way? how do they work?
@KevinZhao : The 2 then gets executed sequentially, 1st then is to get text from the response object and the 2nd one is to print text value.
2

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

1 Comment

Hi, if i need to put a token, where i put then?
0

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.

Comments

0

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] ]

3 Comments

<Button onPress={this._onPressButton} title="get json data" color="#841584" />
☝︎I need make button like this sorry
And I think no work local and http host like that shit "localhost:3000/api/signup"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.