0

I'm trying to call an API with fetch from React Native App but it doesn't log the response data (console.warn('data', data)) for some reason. It prints the 'call to getArtists' log but then nothing happens.

const URL = 'https://jsonplaceholder.typicode.com/posts'

function getArtists(){
  console.log('call to getArtists')
  return fetch(URL)
    .then(response => response.json())
    .then(data => {
      console.warn('data', data)
    })
}

Code is available here: https://snack.expo.io/rkzea2Zlm at components/api-client.js

What am I doing wrong?

3
  • 1
    you need to return data too Commented Jun 3, 2018 at 19:33
  • I noticed using URL = 'https://facebook.github.io/react-native/movies.json' makes the request works. But others doesnt Commented Jun 3, 2018 at 20:37
  • I noticed if a print responseJSON instead of data it works, but I dont understand. The real API I need (LastFM) doesnt work Commented Jun 3, 2018 at 21:09

1 Answer 1

2

First in your "api_client.js", put a return inside like the code bellow.

function getArtists(){
  console.log('call to getArtists')
  return fetch(URL)
    .then(response => response.json())
    .then(data => {
      return data
    })
}

In your App.js just do that inside componentWillMount.

componentDidMount(){
    getArtists()
      .then(data => {
        alert(JSON.stringify(data))
      });
  }
Sign up to request clarification or add additional context in comments.

4 Comments

You have a wrong "then" in your fetch, just do like this code. function getArtists(){ console.log('call to getArtists') return fetch(URL) .then(response => response.json()) .then(data => {return data}) }
Works after remove the last then in getArtists() method inside api_client.js. I test with alert(JSON.stringify(data)) in componentWillMount.
Thanks! Yes, seems working. But I dont understand why console.log(data) doesnt print the information but alert does it. Maybe related to snack (?)
Problably it's not working with two parameters (Ex.: console.log("teste", data)). If you insert only one parameter will work.

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.