Search code examples
reactjsflickraxios

Flickr api not fetching images using React and Axios


I am trying to fetch a list of images from tags but nothing is being console logged or rendering out. Not sure If I am missing a parameter with the api.

CODEPEN: http://codepen.io/anon/pen/PWgBgd?editors=0010

const url = "https://api.flickr.com/services/feeds/photos_public.gne?tags=kitten&format=json"

class App extends React.Component {
  constructor() {
    super()
    this.state = {
      items: []
    }
  }

  componentWillMount() {
    axios.get(url)
      .then((response) => {
        console.log(response.data.jsonFlickrFeed.items);
            this.setState({
                items: response.data.jsonFlickrFeed.items
            })
      })
      .catch((err) => {
      })
  }

  render() {
        const mappedStorage = this.state.items.map((item) => <li>{item.media.m} </li>)

    return (
      <div>
       hello
                <ul>{mappedStorage}</ul>
      </div>
    );
  }

}

ReactDOM.render(<App />, document.body)

Solution

  • Found the problem, Flickr does some weird stuff with their api unless you pass in the right stuff. Set the url to:

    http://api.flickr.com/services/feeds/photos_public.gne?tags=kitten&format=json&nojsoncallback=true

    and then update code to be

    axios.get("https://api.flickr.com/services/feeds/photos_public.gne?tags=kitten&format=json&nojsoncallback=true") 
      .then((response) => {
        console.log(response.data.items);
        this.setState({
            items: response.data.items
        })
      })
      .catch((err) => {
      console.log(err)
      })
    

    seems the main thing is if you dont add nojsoncallback=true the JSON they return is a callback function which isn't parsable by normal means luckily they give you a param to return what you want.

    working pen http://codepen.io/finalfreq/pen/WRWgPw?editors=0011