Search code examples
javascriptarraysreact-nativesetstatereact-native-sectionlist

setState in a nested array object for SectionList data by index


I'm trying to fill a SectionList with data from a SQLite database.

I start here:

  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: []
          }
        ]
      };
    }

I fetch the data from the database and when I go to setState to the appropriate place it doesn't take.

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

Each of the functions is built the same, fetching data from their respective database:

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)}        
          );
      }
  )};

console.log(bulls) will return an array of data as expected. console.log(this.state.sectionListData[0].data) will return 'undefined'. I cannot see to get it to update the index for the nested array for the SectionList.


Solution

  • Maybe you should set a local variable first to save the current state and then update the state from that local variable

    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)}        
              );
          }
      )};