Having trouble displaying a "SectionList" in "React Native", it's just not cooperating

As a newcomer to programming, I recently started working with React Native. I attempted to create a FlatList, which was successful, but the data did not display as I intended. I realized I needed a header to organize the data the way I wanted, so I discovered the <SectionList> component. I modified the code to incorporate it, but upon adding the data, I encountered the following error:

(property) sections: readonly SectionListData<any, GamesInfoSection>[]
An array of objects with data for each section.

No overload matches this call.
  Overload 1 of 2, '(props: SectionListProps<any, GamesInfoSection> | Readonly<SectionListProps<any, GamesInfoSection>>): SectionList<...>', gave the following error.
    Type 'GamesInfoSection[] | undefined' is not assignable to type 'readonly SectionListData<any, GamesInfoSection>[]'.
      Type 'undefined' is not assignable to type 'readonly SectionListData<any, GamesInfoSection>[]'.
  Overload 2 of 2, '(props: SectionListProps<any, GamesInfoSection>, context: any): SectionList<any, GamesInfoSection>', gave the following error.
    Type 'GamesInfoSection[] | undefined' is not assignable to type 'readonly SectionListData<any, GamesInfoSection>[]'.
      Type 'undefined' is not assignable to type 'readonly SectionListData<any, GamesInfoSection>[]'.ts(2769)
SectionList.d.ts(210, 3): The expected type comes from property 'sections' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<SectionList<any, GamesInfoSection>> & Readonly<...>'
SectionList.d.ts(210, 3): The expected type comes from property 'sections' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<SectionList<any, GamesInfoSection>> & Readonly<...>'

This is the complete component:

 <SectionList

            sections={games}
            keyExtractor={(item, index) => item + index}
            renderItem={({ item }) => (

              <View style={styles.game_section}>

                <View style={styles.game_match}>
                  <View style={styles.game_time}>
                    <Text>{item.games?.time}</Text>
                  </View>

                  <View style={styles.breakLine}>
                  </View>

                  <View style={styles.game_team}>
                    <View style={styles.team}>
                      <View style={styles.team_brand}></View>
                      <Text style={styles.team_name}>{item.games?.home}</Text>
                    </View>


                    <View style={styles.team}>
                      <View style={styles.team_brand}> </View>
                      <Text style={styles.team_name}>{item.games?.away}</Text>
                    </View>


                  </View>

                  <View style={styles.breakLine}>
                  </View>

                  <View style={styles.score}>
                    <View style={styles.team}>
                      <Text style={styles.team_name}>{item.games?.homeScore}</Text>
                    </View>


                    <View style={styles.team}>
                      <Text style={styles.team_name}>{item.games?.homeScore}</Text>
                    </View>

                  </View>
                </View>
              </View>


            )}
            renderSectionHeader={({ section: { infoSection } }) => (

              <View style={styles.game_info}>
                <Text style={styles.game_country}>{infoSection?.country}</Text>
                <Text style={styles.game_league}>{infoSection?.league}</Text>
              </View>
            )}

          />
        

This is the data const:

const [games, setGames] = useState<GamesInfoSection[]>();

  useEffect(() => {

    try {
      const api = setupApiGames();
      api?.get('/games').then(response => {

        setGames(response.data);

      }
      )
    } catch (error) {
      console.log(error + 'error ao acessar os Jogos');
    }

  }, [])

I attempted to implement the suggested solution by VScode:

  sections={games as any}
            keyExtractor={(item, index) => item + index}
            renderItem={({ item }) => (

However, this did not resolve the issue. The error disappeared, but the application did not display anything other than a blank white page, even after removing components outside of the "SectionList".

Answer №1

You are providing an empty array that does not match the expected data structure for SectionList:

Here is a sample set of data that fits the SectionList format:

const DATA = [
  {
    title: "Main courses",
    data: ["Pizza", "Burger", "Risotto"]
  },
  {
    title: "Side dishes",
    data: ["French Fries", "Onion Rings", "Fried Shrimps"]
  },
  {
    title: "Beverages",
    data: ["Water", "Coke", "Beer"]
  },
  {
    title: "Desserts",
    data: ["Cheese Cake", "Ice Cream"]
  }
];

GamesInfoSection type should match this data structure.

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

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...

How to send form group in Angular when the enter key is pressed

When I press the submit button on a form, it sends a request to the database to filter data in a grid. However, I also want the form to submit when the enter key is pressed. HTML <form [formGroup]="bmForm" (keyup.enter)="onSearchClic ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...

Error in Radix UI encountered while attempting to use "react-accordion"

Trying to import the root component of a react accordion and then export it in my project with the name Accordion. However, I keep getting a type error that says Unsafe assignment of an `any` value. I've attempted to fix it by using the as keyword but ...

Ensuring type safety for a generic union type

A new union type has been defined: type CustomParameterType = number | string | boolean | Array<number>; An object is created to hold key-value pairs of this union type: class CustomParameter { constructor(name: string, value: CustomParameter ...

What is the best way to showcase a view on the same page after clicking on a link/button in Angular?

Is there a way to show a view on the same page in an Angular application when a link is clicked? Rather than opening a new page, I want it displayed alongside the list component. How can this be accomplished? Here's an illustration of my goal: I&apos ...

Expo - Cli installation issue: encountering difficulties in installing the Expo CLI

Whenever I attempt to launch expo, it prompts me to install it. However, after installing it, I receive a message indicating that it has been successfully installed, only to be told again to install it. ...

Reset Angular Material autocomplete upon selection

The issue I'm encountering is as follows: when an option is chosen from the autocomplete input, it should not only add a chip to the Angular Material Chips component (which it currently does), but also clear the autocomplete input so that another opti ...

Error: BrowserModule has already been loaded

After updating my application to RC6, I encountered a persistent error message: zone.js:484 Unhandled Promise rejection: BrowserModule has already been loaded. If you need access to common directives like NgIf and NgFor from a lazily loaded module.. ...

Using Angular2, assign a value to the session and retrieve a value from the session

I am having trouble getting and setting a session. Here is my code: login_btnClick() { var NTLoginID = ((document.getElementById("NTLoginID") as HTMLInputElement).value); this._homeService.get(Global.BASE_USER_ENDPOINT + '/EmployeeDe ...

The Angular Observable continues to show an array instead of a single string value

The project I am working on is a bit disorganized, so I will try to explain it as simply as possible. For context, the technologies being used include Angular, Spring, and Maven. However, I believe the only relevant part is Angular. My goal is to make a c ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Installing local dependencies in Node can be done as a shortcut by nesting them instead of having them

It appears that the issue arose after updating node/npm, but I only noticed it recently when I had to delete and recreate my node_modules folder. In my React Native project, there is a core module and an Examples project used to demonstrate the module. Th ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Accessing a child field from Firebase in a React Native application

My firebase data is structured like this: "Locations" : { "location01" : { "image" : "https://www.senecacollege.ca/content/dam/projects/seneca/homepage-assets/homepage_intl.jpg", "instructorNa ...

Tips for refreshing a React component using incremental changes retrieved from an API

I am developing a unique React application using Next.js and TypeScript, with an api-backed data set in one component that needs to be cached indefinitely. Unlike traditional examples I have found online, my component must: Fetch only the most recent 100 ...

Ensuring the Presence of a Legitimate Instance in NestJS

I have been working on validating my request with the Product entity DTO. Everything seems to be in order, except for the 'From' and 'To' fields. The validation works correctly for the Customer and Type fields, but when incorrect data i ...

Tips on transferring information to the graphical user interface

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

I am not currently working on developing an angular application

Seeking assistance for the issue described below, as I have been struggling with it for three days. Any help would be greatly appreciated. Despite multiple attempts, the situation only seems to worsen with each try. The problem arises when attempting to ...