简体   繁体   中英

Load more data on scroll

I have a page with a search input, once the user clicks on submit the results come up.

There can be a lot of results (usually not but there can be thousands of results) and I don't want to load them all at once, how can I get a few dozens and fetch more results from he API as the user scrolls down, what's the correct way to do that? I was thinking that Lodash throttle can fit but I couldn't find a good example for it.

This is my react component:

const getContacts = async (searchString) => {
  const { data: contactsInfo} = await axios.get(`api/Contats/Search?contactNum=${searchString}`);
  return contactsInfo;
};
export default class Home extends React.Component {
  state = {
    contactsInfo: [],
    searchString: '',
  };

  handleSubmit = async () => {
    const { searchString } = this.state;
    const contactsInfo = await getContacts(searchString);
    this.setState({ contactsInfo });
  };

  onInputChange = e => {
    this.setState({
      searchString: e.target.value,
    });
  };

  onMouseMove = e => {

  };

  render() {
    const { contactsInfo, searchString, } = this.state;
    return (
          <div css={bodyWrap} onMouseMove={e => this.onMouseMove(e)}>
            <Header appName="VERIFY" user={user} />
            {user.viewApp && (
              <div css={innerWrap}>
                <SearchInput
                  searchIcon
                  value={searchString || ''}
                  onChange={e => this.onInputChange(e)}
                  handleSubmit={this.handleSubmit}
                />
                     {contactsInfo.map(info => (
                      <SearchResultPanel
                        info={info}
                        isAdmin={user.isAdmin}
                        key={info.id}
                      />
                    ))}
              </div>
            )}
            <Footer />
          </div>

    );
  }
}

If the API supports pagination then you can use React-Infinite-Scroll . It looks like this

  <div style="height:700px;overflow:auto;">
    <InfiniteScroll
        pageStart={0}
        loadMore={loadFunc}
        hasMore={true || false}
        loader={<div className="loader">Loading ...</div>}
        useWindow={false}>
      {items}
    </InfiniteScroll>
  </div>

However if the REST API does not support it, you can still load the data and show them in chunks to the user with the same library but you would need to handle the current load state by yourself.

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