Home > front end >  Displaying json data with parent and two childs using sectionlist/flatlist in reac-native
Displaying json data with parent and two childs using sectionlist/flatlist in reac-native

Time:04-13

I am still new in react-native networking and I want to display json data using sectionlist Here is my code

  import * as React from 'react';
 import { Button, View ,Pressable,Text,StyleSheet,ActivityIndicator,FlatList,SectionList} from 'react-native';
 import { createDrawerNavigator } from '@react-navigation/drawer';
 import { NavigationContainer } from '@react-navigation/native';
 import { createStackNavigator } from '@react-navigation/stack';
import { Component } from 'react/cjs/react.production.min';
 const Drawer = createDrawerNavigator();
 const Stack=createStackNavigator();
 export default class ScreenA extends Component {
 constructor(props) {
  super(props);

  this.state = {
    data: [],
    isLoading: true
  };
}

async getData() {
  try {
    const response = await fetch('https://mocki.io/v1/d479a871-9165-45a1-a43d-cd2ae3e68845');
    const json = await response.json();
    this.setState({ data: json });
  } catch (error) {
    console.log(error);
  } finally {
    this.setState({ isLoading: false });
  }
}

componentDidMount() {
  this.getData();
}

render() {
  const { data, isLoading } = this.state;

  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.firstName}, {item.lastName}</Text>
          )}
        />
      )}
    </View>
  );
}
};

Json link:https://mocki.io/v1/d479a871-9165-45a1-a43d-cd2ae3e68845 Please, any help will be highly appreciated.Thanks in advance

CodePudding user response:

I guess it should be like this.

<FlatList
      data={this.state.data} // you should add this.state
      keyExtractor={({ id }, index) => id}
      renderItem={({ item }) => (
        <Text>{item.firstName}, {item.lastName}</Text>
      )}
    />
  • Related