javascripttypescriptreact-nativeflatlist

FlatList not shown result in React native


I am new to React native and i am trying to create a simple flatlist and fill it from Api https://dummyjson.com/products but it never show results ... here is my App.tsx code

import React from 'react';
import type {PropsWithChildren} from 'react';
import {
  FlatList,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';
import ShopList from './ReusableComponents/ShopList';
import axios from 'axios';
import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

type SectionProps = PropsWithChildren<{
  title: string;
}>;


function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const shops: ArrayLike<any> | null | undefined = []




    fetch('https://dummyjson.com/products')
    .then(response => response.json())//hat el jsonresponse law rege3
    .then(result => { shops })

    console.log({shops})

  
  return (
    
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
     
     <ShopList />
      
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
  edges: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 5,
    minWidth: 50
  }
});

export default App;

And here is ShopList code

import React, {Component} from 'react';

import {
  View,
  FlatList,
  Image
} from 'react-native'
import ShopListRow from '/Users/nb29042/Desktop/React/DemoShop/ReusableComponents/ShopListRow';
import { ListItem, Avatar } from 'react-native-elements';

export default class ShopList extends Component {
  constructor(props){
    super(props);
    this.state = {
      shops: []
    }
  }


      fetchItem() {
        requestAnimationFrame(() =>
          fetch(`https://dummyjson.com/products`, {
            method: 'GET',
          })
            .then(response => response.json())
            .then(responseJson => {
              this.setState({shops: responseJson})
              // console.warn(this.state.shops);
            })
            .catch(error => {
              {
                alert(error)
              }
            }),
        );
    }
  
    componentDidMount(){
      this.fetchItem()
    }

    
      render() {
        return (

          <View style={{
            flex: 1,
            backgroundColor: '#FFFFFF'
          }}>
    
            
    
            <FlatList
              data = {
                this.state.shops
              }
              renderItem={({ item, index }) => 
                {
                  return <ShopListRow 
                  shop={item} 
                  index={index} 
              
                />}
                
    
              }
              keyExtractor={item => item.id}
              initialNumToRender={16}
              extraData={this.state}
            />

    
          </View>
        );
      }
}

And the ShopListRow Code is:

import React, {Component} from 'react';

import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  FlatList,
  Image
} from 'react-native'
//import Stars from './Stars';
export default class ShopListRow extends Component {
    render() {

        const {
          shop,
          index
        } = this.props
        
        return (
          <View key={shop.id} style={{ backgroundColor: index % 2 === 0 ? 'white' : '#F3F3F7' }}>
    
            <View style={styles.row}>
              
    
              <View >
                <Text>{shop.title}</Text>
                <Text >{shop.description}</Text>
              </View>
    
              <View style={styles.edges}>
                
                <TouchableHighlight 
                  //onPress={this.infoPressed}
                  style={styles.button}
                  underlayColor='#5398DC'
                >
                  <Text style={styles.buttonText}>Info</Text>
                </TouchableHighlight>
    
    
              </View>
            </View>
    
          </View>
        )
      }
}


const styles = StyleSheet.create({
    row: {
      flexDirection: 'row'
    },
    edges: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 5,
      minWidth: 50
    },
    stars: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'row',
      justifyContent: 'flex-start',
      padding: 5,
      minWidth: 50
    },
    nameAddress: {
      flexDirection: 'column',
      flex: 8,
      padding: 5
    },
    addressText: {
      color: 'grey'
    },
    button: {
      borderWidth: 1,
      borderColor: '#0066CC',
      borderRadius: 14,
      paddingHorizontal: 10,
      paddingVertical: 3,
      backgroundColor: '#fff',
    },
    buttonText: {
      color: '#0066CC',
      fontSize: 12
    },
    info: {
      marginHorizontal: 40,
      marginVertical: 10,
      padding: 10,
      backgroundColor: '#fff',
      borderWidth: 1,
      borderColor: '#ddd',
      borderRadius: 4
    }
  })
  

if anyone can help me why flatlist results not shown any results i will be thankful... best regards


Solution

  • The response from https://dummyjson.com/products is an object.

    {
         products: [....]
     }
    

    In your ShopList component, you're setting the shop's array to an object. Update your fetch items function and use the products array.

    fetchItem() {
      requestAnimationFrame(() =>
        fetch(`https://dummyjson.com/products`, {
          method: 'GET',
        })
          .then(response => response.json())
          .then(responseJson => {
            this.setState({shops: responseJson.products}) // <--- here
          })
          .catch(error => {
            {
              alert(error)
            }
          }),
      );
    }