0

New to React Native here... I'm trying to call a function that does a get request inside a component which is in the render() method.

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

export default class Home extends React.Component {
  static navigationOptions = {
    title: 'Details',
  };

  getMoviesFromApiAsync = () => {
    return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
  };

  render() {

    return (
      <React.Fragment>
        <Text>{getMoviesFromApiAsync()}</Text>
      </React.Fragment>
    );
  }
}

However, I'm getting ReferenceError: Can't find variable getMoviesFromApiAsync(). Why is this?

Error Image

David Pham
  • 187
  • 1
  • 4
  • 14

1 Answers1

1

You need to call the method on your class, this is a basic Vanilla Javascript thing.

<Text>{this.getMoviesFromApiAsync()}</Text>

However, your approach here is not good, you should write the component out to store the results from your api request in component state. this way you dont need to make a request every render cycle!

export default class Home extends React.Component {
  static navigationOptions = {
    title: 'Details',
  };

  state = {
    movies: []
  }

  componentDidMount() {
    this.getMoviesFromApiAsync()
  }

  getMoviesFromApiAsync = () => {
    return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        movies: [...this.state.movies, ...responseJson.movies]
      })
    })
    .catch((error) => {
      console.error(error);
    });
  };

  render() {
    const { movies } = this.state
    return (
      <React.Fragment>
        { movies.map( (movie, i) => <Text>{movie.title}</Text> ) }
      </React.Fragment>
    );
  }
}
John Ruddell
  • 25,283
  • 6
  • 57
  • 86
  • Wow. Can't believe I missed this..I'm an idiot, thanks! – David Pham Mar 13 '19 at 21:01
  • @DavidPham see my most recent edit. you should refactor your component to at least use state to store results (simple example I provided). If this solves your issue, when you can I'd greatly appreciate it if you accept the answer :D – John Ruddell Mar 13 '19 at 21:05