Search code examples
androidreactjsreact-nativetokenunexpected-token

React Native Networking Unexpected Token in Function


I am currently trying to learn React Native, but I already struggle in the Networking Part of the Tutorial.

This is the code:

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

class App extends Component {
    function 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() {
        getMoviesFromApiAsync();
    };
}

AppRegistry.registerComponent('testproject', () => App);

And I get the following error:

enter image description here

In my case Line 5, Char 10 would be: function so it expects something else after funct.


Solution

  • Here is an example of using that function:

    import React, { Component } from 'react';
    import { AppRegistry, Text, TextInput, View } from 'react-native';
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.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: responseJson.movies });
                })
                .catch((error) => {
                    console.error(error);
                });
        }
        renderMovies = () => 
           this.state.movies.map((movie, i) => <Text key={i}>{movie.title}</Text>)
    
        render() {
          return (
            <View style={{flex: 1}}>
              {this.renderMovies()}
            </View>
          )
        };
    }
    
    AppRegistry.registerComponent('testproject', () => App);