2

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?

1
  • As of fetch is happening async I would put the fetch in componentWillMount and set the result in state. Then in render use this.state.myjsonresult. If you put the async function inside the render it does not trigger rerender when finished Commented Jan 17, 2018 at 12:17

2 Answers 2

2

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} ... />
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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>
    );
  }
}

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.