1
alert(fetch('https://facebook.github.io/react-native/movies.json')  
    .then(function(response) {
        return response.json()['description']
    }))

I was expecting Your app fetched this from a remote endpoint! but apparently, this is just an Object?

According to the other answers I've checked, like this one, this should work perfectly.

enter image description here

Community
  • 1
  • 1
User
  • 23,729
  • 38
  • 124
  • 207

2 Answers2

1

response.json returns a Promise

.then(function(response) {
    return response.json()
})
.then(function(data) {
   return data.description
})
.then(function(description) {
    alert(description)
 })
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • How many open brackets/braces are before this? There are 2 brackets on the 3rd line, but the other `then` statement only 1, for example, and no semi-colon. – User Mar 30 '17 at 19:27
  • Still better than callback hell. BTW you could use arrow functions if don't care much about old browsers. `fetch(blah).then(x => x.json()).then(data => alert(data.description))` - no brackets at all :) – Yury Tarabanko Mar 30 '17 at 19:27
  • So there's no way to get the data out of there? I want to save this as a variable and use it elsewhere in my code. – User Mar 30 '17 at 19:35
  • You can save promise as a variable say `gettingData = fetch().then(x => x.json())` and use it later still knowing it is a Promise `gettingData.then(data => /* do something with data*/)`. Plz read this question to get better understanding of what the problem with async code is about http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Yury Tarabanko Mar 30 '17 at 19:39
0

You can access the description as shown below.

To save the value and use it later, you can use states (aka Component States).

.then(function(response) {
    var resJson = response.json();
    var des = resJson['description'];
    this.setState(
         { 
             description: des 
         }
    )

    }))

You can define your states in the React Component like so:

class MyClass extends Component {

    state = {
        description: ""
    }

And retreive the state like so:

var currentState = this.state.description;
john
  • 1,561
  • 3
  • 20
  • 44