Sazzad Hossain
Sazzad Hossain

Reputation: 57

How can I load data from a JSON file which is stored at GitHub in React Native?

I have the following JSON file in my GitHub and want to load it:

{"Cat": [
    {"key": "a", "title": "Bangladesh", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/bangladesh.jpg"},
    {"key": "b", "title": "Sports", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/sports.jpg"},
    {"key": "c", "title": "Politics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/politics.jpg"},
    {"key": "d", "title": "Entertainment", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/entertainment.png"},
    {"key": "e", "title": "Economics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/economics.jpg"},
    {"key": "f", "title": "Technology", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/technology.jpg"},
    {"key": "g", "title": "Others", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/m.jpg"}
]}

I tried to use the following code to fetch it:

getMoviesFromApiAsync() {
  return fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.Cat;
    })
    .catch((error) => {
      console.error(error);
    });
}
<FlatList horizontal= {true}
   data={this.getMoviesFromApiAsync()}
   renderItem={({item}) => (                
      <TouchableOpacity
        style={styles.catOption}
        onPress = { ()=> this.setState({ name: item.title })}
      >
         <Image
            style={styles.imgButton}
            source={{uri: item.image}}
          />
          <Text style={styles.buttonText}>{item.title}</Text>
       </TouchableOpacity>
       )
  }
/>

However, no data is loaded from the JSON file. What's the problem?

Upvotes: 2

Views: 2311

Answers (2)

Mudassir Zakaria
Mudassir Zakaria

Reputation: 437

Read this link

Use this code:

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

export default class Movies extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true
    }
  }

  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.setState({
          isLoading: false,
          dataSource: ds.cloneWithRows(responseJson.movies),
        }, function() {
          // do something with new state
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
        />
      </View>
    );
  }
}

Upvotes: 2

parohy
parohy

Reputation: 2180

As your fetch is triggered when the list is rendered, the result of the fetch is not set. In order to re-render the list with data I would suggest to set the result inside the state of the Component. This will trigger a re-render and you should be able to see the list after the fetch resolves:

class MyComp extends Component {
    state = { result: [] }
    componentWillMount(){
      this.getMoviesFromApiAsync()
    }

    getMoviesFromApiAsync = () => fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
     .then((response) => response.json())
     .then((responseJson) => {
        this.setState({ result: responseJson.Cat });
     })
     .catch((error) => {
        console.error(error);
     })

    render(){
      <FlatList data={this.state.result} ... />
    }
}

Upvotes: 2

Related Questions