Ryan
Ryan

Reputation: 17

Exporting JSON from fetch in React Native

I am working on exporting the JSON I get from a fetch. I know I have a binding issue, but I'm not completely sure on how I should proceed to bind my function to the current component. I have a quick example at this URL https://snack.expo.io/@mcmillster/c21pbG.

app.js

  import React from 'react';
    import { FlatList, ActivityIndicator, Text, View  } from 'react-native';
    import { getMovies } from './utility.js';

    export default class FetchExample extends React.Component {

    constructor(props){
      super(props);
      this.state ={ 
      isLoading: true,
    }
    this.getMovies = getMovies.bind(this)
    }

    componentDidMount(){
    this.getMovies;
    }



    render(){

      if(this.state.isLoading){
        return(
          <View style={{flex: 1, padding: 100}}>
            <ActivityIndicator/>
          </View>
        )
      }

      return(
        <View style={{flex: 1, paddingTop:20}}>
          <FlatList
            data={ this.state.data }
            renderItem={({item}) => <Text>{item.title}, {item.releaseYear} 
 </Text>}
            keyExtractor={({id}, index) => id}
          />
        </View>
      );
    }
  }

utility.js

export function getMovies() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          data: responseJson.movies,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
    }

Upvotes: 1

Views: 991

Answers (2)

Milore
Milore

Reputation: 1672

I think you should not try to set the state from your fetch function. Just call it, return data and handle them in your component.

app.js

[...]
private getMovies = async() => {
  const movies = await getMovies();
  if(movies){
    this.setState({...})
}

componentDidMount(){
  this.getMovies();
}

utility.js

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

Upvotes: 0

AnonymousSB
AnonymousSB

Reputation: 3604

In your componentDidMount lifecycle hook, you're not calling the getMovies function, you're just referencing it. Change this.getMovies to this.getMovies()

Solution

componentDidMount(){
  this.getMovies();
}

Upvotes: 0

Related Questions