Search code examples
reactjsaxiosmaterial-uiflickr

Set images state to Flickr API Response


I’m working on a Flickr clone, where an axios GET request is sent to retrieve photos as the user types into the input. My current path is returning undefined. Where is the response array of objects so I know where to set the images state to? Thank you!

Search Container

import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import axios from 'axios';
class Search extends Component {
  state = {
    searchText: '',
    images: []
  }

  onTextChange = (e) => {
    this.setState({searchText: e.target.value}, () => {
      axios.get('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ea72b9024308d54ba48382706bebb960&user_id=156981303%40N08&format=json&api_sig=f8866cedaa88ceccdfe1e1cf06dcaded')
      .then(response => {
        this.setState({images: response.???});
      })
      .catch(error => {
        console.log(error)
      });
    });
  }

  render() {
    console.log(this.state.images);
    return (
      <div>
        <TextField 
        name="searchText"
        value={this.state.searchText}
        onChange={this.onTextChange}
        floatingLabelText="Search for photos"
        fullWidth={true} 
        />
      </div>
    );
  }
}

export default Search;

Solution

  • try to modify your onTextChange method to this:

    onTextChange = e => {
    this.setState({ searchText: e.target.value }, () => {
      axios
        .get(
          `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ea72b9024308d54ba48382706bebb960&tags=${this.state.searchText}&tag_mode=any&format=json&nojsoncallback=1`
        )
        .then(response => response.data)
        .then(response => this.setState({ images: response.photos.photo }))
        .catch(error => {
          console.log(error);
        });
      });
    }