0

So, I can't figure out why the last line in my code ends up displaying an error, and I couldn't find any other posts that help in my particular case. Here's the code:

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class AlbumList extends Component {
  state = { albums: [] };


componentWilMount() {
  fetch('https://rallycoding.herokuapp.com/api/music_albums')
  .then(response => response.json())
  .then(response => this.setState({ albums: response.data }));
}

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

  render() {
    console.log(this.state.albums);
  }

  return() {
  <View>
  {this.renderAlbums()}
  </View>
}
1
  • It is also not advisable to make API calls inside componentWillMount as the data might not be fully retrieved before the component renders. Commented Apr 16, 2018 at 13:25

1 Answer 1

1

Because you call return like method, but return should be in your render() method.

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class AlbumList extends Component {
  state = { albums: [] };


  componentWilMount() {
    fetch('https://rallycoding.herokuapp.com/api/music_albums')
      .then(response => response.json())
      .then(response => this.setState({ albums: response.data }));
  }

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

  render() {
    console.log(this.state.albums);
    return (
      <View>
      {this.renderAlbums()}
    </View>
    );
  }
} 
Sign up to request clarification or add additional context in comments.

Comments

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.