Set the state of a nested array object within SectionList data using the index

I'm currently working on populating a SectionList with data retrieved from a SQLite database.

Here is where I begin:

  constructor(props) {
    super(props);
      this.state = {
        loading: true,
        sectionListData: [
          {
            title: 'A Bulls',
            data: []
          },
          {
            title: 'H Bulls',
            data: []
          },
          {
            title: 'C Bulls',
            data: []
          },
          {
            title: 'R Bulls',
            data: []
          }
        ]
      };
    }

Upon fetching the data from the database, setting the state to the appropriate location seems to be ineffective.

componentDidMount() {
    this.aBulls();
    this.cBulls();
    this.hBulls();
    this.rBulls();
}

All the functions are structured similarly, pulling data from their respective databases:

aBulls() {
  db.transaction(
    tx => {
    //SQL Statement
        tx.executeSql("select * from abulls group by reg",
    //Arguments
        [],
    //Success
        (tx, { rows: {_array} }) => {
          const handlebull = JSON.stringify(_array);
          const bulls = JSON.parse(handlebull);
          this.setState({sectionListData: [
            {
              0: 
                {
                  data: bulls
                }
            }
          ]
          });
          this.setState({loading: false});
        },
    //Error
        (error) => {console.log(error)}        
          );
      }
  )};

While console.log(bulls) provides the expected array of data, console.log(this.state.sectionListData[0].data) outputs 'undefined'. I am facing difficulty updating the index for the nested array within the SectionList.

Answer №1

Consider creating a local variable to store the current state before updating it.

aBulls() {
  db.transaction(
    tx => {
    //SQL Statement
        tx.executeSql("select * from abulls group by reg",
    //Arguments
        [],
    //Success
        (tx, { rows: {_array} }) => {
          const handlebull = JSON.stringify(_array);
          const bulls = JSON.parse(handlebull);
          let sectionListData = this.state.sectionListData;
          sectionListData[0].data = bulls;
          this.setState({sectionListData, loading: false});
        },
    //Error
        (error) => {console.log(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

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

Obtaining data from event listener during interval execution

I recently developed a countdown timer using JavaScript and included an event listener for a stop button to pause the timer When I stopped the timer, every second was being logged individually but I wanted to only retrieve the final time value. For exampl ...

Using a JavaScript variable within an AngularJS scope

Currently in the process of building a webpage with the MEAN stack, I utilized the HTML5/Javascript sessionStorage variable to store the user data for access across all pages. Now, the challenge is passing this data into angularJS through the controller w ...

Issue with React hooks: Callback functions from library events (FabricJS) not receiving the updated state values

Why am I not receiving the updated state values within FabricJS events like object:modified, mouse:up, etc... even though I can set state values inside those callback functions. Upon attempting to retrieve the state value, it consistently returns the init ...

Storing raw HTML in a Mysql database, then fetching and displaying it on a webpage

I'm having an issue with my application. It's a form builder that allows users to create their own forms and then save them for later use. The HTML code generated by the form builder is stored in a MySQL database. However, when I try to retrieve ...

jQuery validation: Form failing to pass validation

I have encountered an issue with a simple JavaScript file on my ASP.NET MVC website. While the input masking feature works smoothly, the form validation seems to be malfunctioning. Even when I enter a phone number that is only 4 digits long, the validation ...

React blank state - State remains undefined after calling setState

I took out the imports because they are not causing any issues When I render, I set my state and it logs correctly in the console. However, when I try to map it, it comes back as null and gives me an error stating that there are no elements in the "allInf ...

jQuery: Track mouse movement with a delay

I'm looking to create a div that follows cursor movement with a slight delay, similar to the effect seen on this website: In the example link provided, you can observe that the 'follower' has a brief delay in its animation. I attempted to ...

A method in JavaScript to fetch a single variable using the GET request

Although I am new to writing JavaScript, I am currently working on an iOS application that will make use of JavaScriptCore's framework to interpret a piece of javascript code in order to obtain a specific variable. My goal is to establish a GET reques ...

Having trouble getting the Socket.io package to install on Node.js in Windows 7?

Hey there! I'm having trouble installing the socket.io module using npm install socket.io. Unfortunately, I encountered the following error: npm WARN package.json <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8f80c3869 ...

The jQuery event for clicking is not functioning as expected when trying to display particular data from a JSON array

Three dummy users were created with a JSON array structured like this: var userArray = {"users":[ {"Name":"User1","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2f293f286b1a2935373f2e3233343d74393537">[email& ...

How can I detect click events on SVG path element using Angular?

Is it possible to detect click events on SVG elements such as path or g using Angular? To see an example of this, check out this demo. Right now, if a (click) event binding is added to the svg elements, the click() event handler will trigger. However, how ...

Issues arise when attempting to enforce type-safety in TypeScript while using the JSON.parse

Is it possible that type-safety is compromised in TypeScript when dealing with JSON parsing? I should be triggering an error, but I'm not: interface Person { name: string } const person: Person = somePossibleFalsey ? JSON.parse(db.person) : undefi ...

Displaying saved locations on Google Maps API

Recently, I delved into experimenting with the Google Maps API and AJAX integration. While I encountered various challenges along the way, I managed to overcome them. However, I've hit a roadblock now. I was following a well-written and detailed tuto ...

Preventing ReactJS tooltips from exceeding the boundaries of the screen

Here is a simple demo showcasing blocks with tooltips that appear when hovered over. However, there seems to be an issue with the functionality. The tooltip should ideally be displayed either from the left or right side of the block. To determine the size ...

Chrome is experiencing a delay in closing the Select Option dropdown menu

On my webpage, I have two select option buttons placed on different tabs. Whenever one button is changed, I want to update the value of the other button and assign it to a specific element like a span in the example code provided. While everything works sm ...

Obtain a particular column from a JSON document using Angular 2

Currently, I am working on a project in Angular2 that requires the use of an online JSON file. I have utilized http.get to retrieve the file, but I only need the data from the second and third columns which contain the first name and last name. If you wan ...

What is the solution for the error message "this.filters is not a function" in Vue.js 2?

Here is the code for my component: <script> import _ from 'lodash' export default{ props:['search','category'], data(){ return{ price_min:'', ...

Ways to personalize Angular's toaster notifications

I am currently utilizing angular-file-upload for batch file uploads, where I match file names to properties in a database. The structure of the files should follow this format: 01-1998 VRF RD678.pdf VRF represents the pipeline name RD represents the lo ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...