1

I want to get some data from api and display data in my app. This is my code, class AlbumList extends Component {

state = { albums: [] };

async componentWillMount() {
try {
  const data = await axios.get(
      'https://rallycoding.herokuapp.com/api/music_albums'
  );
  this.setState({ albums: data });
} catch (err) {
  console.error(err.message);
}
}

renderAlbums() {
  return this.state.albums.map(album => <Text>{album.title}</Text>);
}

render() {
return (
  <View>
    {this.renderAlbums()}
  </View>
 );
 }
 }

this will give a error this.state.albums.map is not a function.. any way to solve this?

0

1 Answer 1

1

The error "map it not a function" occurs because axios don't return an array. Axios returns an object with keys like status, data.

const data = await axios.get(
  'https://rallycoding.herokuapp.com/api/music_albums'
);
console.log(data);
console.log(data.data); // album data
this.setState({album: data.data});

When using without await:

axios.get('https://rallycoding.herokuapp.com/api/music_albums')
  .then(response => {
    this.setState({ album: response.data });
  })
  .catch(error => {
    console.log(error);
  });

So you must check the object key "data" returned by axios get.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.