Unable to display results in React Native due to FlatList not being shown

I'm a beginner to React Native and I'm attempting to create a simple flatlist populated from an API at , but unfortunately, no results are displaying. Here's 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;

Here is the 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 here's the ShopListRow code:

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 provide assistance on why the flatlist is not showing any results, I would greatly appreciate it. Best regards!

Answer №1

The data retrieved from this website is in the form of an object.

{
     products: [....]
 }

In your ListShop element, you are assigning the shop's array to an object. To correct this, update your fetch items method and utilize the products array instead.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting a Mocha test to display two decimal places in Javascript? Both Big and Decimal libraries are causing issues

After encountering an error with the Big library, I decided to switch to Decimal. First, I ran npm install Decimal Then, I added the following code: const Decimal = require('decimal'); Even after following the examples, my comparison returned { ...

Ways to exhibit API information leveraging the prowess of Ajax

I am looking for a way to utilize the API in order to present data in an organized manner, similar to the following example: Job Title: Agricultural and Related Trades Percentage of Occupancies in Area: 15.41% Unfortunately, my attempt to showcase the d ...

What is the best way to create a fixed array of unchangeable objects?

I am trying to create a class that requires an array of objects as one of its constructor parameters, with the condition that neither the array nor the objects in it can be modified. My current approach involves using the readonly modifier along with the g ...

JavaScript special character encoding techniques

I'm trying to create a function to remove special characters in my JavaScript code. However, whenever I try using chr(46), it throws a syntax error. Does anyone have any suggestions on how I can successfully implement chr(46) in my JS code? storageV ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

Can one manipulate the simulation to make isTrusted=true a reality?

Is there a way to simulate an isTrusted=true in touchStart event triggering? Are there any libraries or workarounds that can make this achievable? When I run the touchStart event programmatically versus physically triggering it, the output differs. Below ...

Tips for creating a tailored Express.js request interface using Typescript efficiently

I have been working on designing a custom Express request interface for my API. To achieve this, I created a custom interface named AuthRequest, which extends Request from Express. However, when attempting to import my interface and define req to utilize t ...

Manipulate the way in which AngularJS transforms dates into JSON strings

I am working with an object that contains a JavaScript date, structured like this: var obj = { startTime: new Date() .... } When AngularJS converts the object to JSON (for instance, for transmission via $http), it transforms the date into a string as ...

The window.open function is creating a new tab using the specified origin or URL

I have a button within an iframe on the webpage "loclahost:3000". When this button is clicked, it should open a new tab with the URL "www.google.com". However, instead of opening the desired URL, the new tab opens with the following incorrect URL: "http:// ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

What is the best way to wrap a call to XMLHttp Request within a $q promise?

I am trying to figure out how to wrap the following code in an AngularJS ui-router resolve section with a $q promise. The goal is to return success or fail based on whether the http request works. Should I encapsulate all of this inside a promise or just ...

Navigating through an ajax-based webpage entirely with selenium webdriver

I have attempted to scroll a page entirely using the following code: var scrollToBottom = function() { window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight)); }; window.on ...

The component `style` requires a callback function as a getter for its configuration, but `undefined` was received instead. Remember to always capitalize component names at the beginning

When working with the MUI library in React Native, I encountered an issue: ERROR Invariant Violation: View config getter callback for component style must be a function (received undefined). Make sure to start component names with a capital letter. I ha ...

Problems encountered when transferring information from jQuery to PHP through .ajax request

Hey there! I am currently working with Yii and facing an issue while trying to pass some data to a controller method called events. This is how my jQuery ajax call looks like: var objectToSend = { "categories" : [selectedOption],"datefrom" : month + "" + ...

Execute JavaScript function on click event in NextJS

Is it possible to execute a JavaScript function on the client side without using addEventListener? This situation works with addEventListener. MyComponent.js import Script from 'next/script' export default function MyComponent({ props }) { ...

Rendering a React component conditionally within the same line

I'm trying to conditionally render a Home component based on a certain condition. I attempted to utilize the Inline If-Else with Conditional Operator recommended by React, as explained in this source. The code snippet I have looks like this: import ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

Transferring information between Flask and JS using AJAX for a Chrome extension

I'm experimenting with AJAX calls to establish communication between my Javascript frontend in a chrome extension and the Flask API where I intend to utilize my Machine Learning algorithms. content.js console.log("Let's get this application ...