简体   繁体   中英

React Infinite Scroll with qwest

I'm currently trying to build a webapp with create-react-app and the packages Infinite-Scroller and qwest

( https://www.npmjs.com/package/react-infinite-scroller )

( https://www.npmjs.com/package/qwest )

my code currently looks like this:

import React, { Component } from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import { darken } from '@material-ui/core/styles/colorManipulator';
import InfiniteScroll from 'react-infinite-scroller';
import qwest from 'qwest';
import * as firebase from 'firebase/app';
import 'firebase/database';

class ShowTable extends Component {

    constructor(props) { // While load / default data
        super(props);
        this.state = {
            listingData: [],
            hasMoreItems: true
        };
    }

    loadItems(page) {
        let dbUrl = 'https://example.firebaseio.com/users.json?limitToLast=1&orderBy="$key"';
        // Variables for InfiniteScrollitems
        let ending = 9390; // Should be updated with get-function below... 
        qwest.get(dbUrl)
            .then(function(xhr, response) {
                let result;
                result = Object.keys(response)[0];
                result = Math.ceil(result / 5) * 5;
                ending = result;
            });

        let that = this;
        let urlDB = 'https://example.firebaseio.com/users.json';
        let startAt = 0;
        let endAt = 5;
        qwest.get(urlDB, {
                orderBy: '"$key"',
                startAt: '"' + startAt + '"',
                endAt: '"' + endAt + '"'
            })
            .then(function(xhr, response) {
                console.log("response is here");
                if (endAt <= ending) {
                    let listingData = that.state.listingData;
                    console.log("i came through if endAt/ending");
                    response.map((dataList) => {
                        listingData.push(dataList);
                    });
                    console.log(listingData);
                    that.setState({
                        listingData: listingData
                    });
                    console.log("i came after setState listingData");
                } else {
                    console.log("i came through else");
                    that.setState({
                        hasMoreItems: false
                    });
                }
                startAt = startAt + 5;
                endAt = endAt + 5;
            });
    }

    render() {
        const { spacing } = this.state;
        const { classes } = this.props;

        const loader = <tr><td><div className="loader">Loading...</div></td></tr>;
        let items = [];
        this.state.listingData.map((tableData, i) => {
            console.log("Test");
            let listA;
            let listB;
            if (tableData.fromListA === "1" && tableData.fromListB === "1") {
                listA = "x";
                listB = "x";
            } else if (tableData.fromListA === "1") {
                listA = "x";
            } else if (tableData.fromListB === "1") {
                listB = "x";
            }
            items.push( 
                <TableRow key={i} data-key={i}>
                 <TableCell>{tableData.userid}</TableCell> 
                 <TableCell>{tableData.username}</TableCell> 
                 <TableCell>{listA}</TableCell> 
                 <TableCell>{listB}</TableCell> 
                 <TableCell>{tableData.lastChecked}</TableCell> 
                </TableRow>
            );
        });

        return ( 
            <Table className={classes.table} id="dataTable">
             <TableHead>
              <TableRow>
               <TableCell>userid</TableCell> 
               <TableCell>username</TableCell> 
               <TableCell>on listA</TableCell> 
               <TableCell>on listB</TableCell> 
               <TableCell>Handle updated</TableCell> 
              </TableRow> 
             </TableHead>

            <InfiniteScroll 
              pageStart={0}
              loadMore={this.loadItems.bind(this)}
              hasMore={this.state.hasMoreItems}
              loader={loader}
              element={'tbody'}
              className={classes.root}
              initialLoad={true}
              useWindow={true} 
             >
              {items} 
            </InfiniteScroll>

           </Table>
        )
    }
}

my 2 problems are the following:

1: I can't update let ending with the qwest.get value I get, I don't know how to do that.

2: I come through the if condition where it says console.log("i came through if endAt/ending") but after that, the script simply doesn't do anything anymore. no console log whatsoever, no items in listingData or anything, and I don't know why. I get one error about keys on the <InfiniteScroll> Element, but it should at least render, but it doesn't. and i can't figure out why.

I'm new to react and still learning so... I'm sorry if it's like a really "dumb" mistake i make here, but I'm actually clueless for 2 days now.

//Edit:

This is my console

错误控制台

Here are my thoughts

  1. I think this is happening because of the nature of the async calls. You're doing your initial qwest.get async, then set some variables and call the second qwest.get before the first one could get the data. If you need the call to be sync'd I'd throw everything after the first qwest.get into it's own function and then call it within the then statement in the first qwest.get . Something like....
qwest.get(dbUrl)
   .then(function(xhr, response) {
      let result = Object.keys(response)[0];
      result = Math.ceil(result / 5) * 5;
      this.continueLoad(result, page)
});
  1. There's a few issues I'm seeing
    • No need for let that = this , just use this
    • You aren't using page anywhere, I think you want to do the following and remove the logic to reset the startAt/endAt variables at the end since they aren't doing anything.
let startAt = 0 + (page - 1) * 5
let endAt = 5 + (page - 1) * 5
  • Change your response.map to a forEach and add some logging to ensure the response and rows are the format you expect. My guess is that the response is not the correct format (in your first qwest.get you use Object.keys(response) before getting data).
console.log("i came through if endAt/ending")
console.log(response)
response.forEach((dataList) => {
   console.log(dataList)
   listingData.push(dataList)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM