Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

reactjs - Use spread operator to combine multiple arrays fetching data in React JS

I want to implement something like infinity scrolling on my application. This is my code:

import React, { useState, useEffect } from "react";

import AsyncSelect from "react-select/async";

const WithPromises = () => {
  const [page, setPage] = useState(1);
  const [allData, setAllData] = useState([]); //here should be added all data
  const [scrolll, setScrolll] = useState();
  const filterData = (inputValue) => {
    const req = fetch(
      `https://jsonplaceholder.typicode.com/todos?_limit=15&_page=${page}`
    )
      .then((response) => response.json())
      .then((res) => {
        const fetchedData = res.map(({ title }) => {
          return {
            label: title,
            value: title
          };
        });
        page > 1 && setAllData([...allData, ...fetchedData]);
        return [...fetchedData, allData];
      });
    return req;
  };

  const promiseOptions = (inputValue) => {
    return filterData(inputValue);
  };

  const scroll = (e) => {
    console.log(e);
    setScrolll(e);
    promiseOptions();
  };

  useEffect(() => {
    setPage(page + 1);
  }, [scrolll, page]);

  return (
    <AsyncSelect
      cacheOptions
      onMenuScrollToBottom={scroll}
      isClearable={true}
      isSearchable={true}
      defaultOptions
      loadOptions={promiseOptions}
    />
  );
};

export default WithPromises;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import React, { useState, useEffect } from "react";

import AsyncSelect from "react-select/async";

const WithPromises = () => {
  const [page, setPage] = useState(1);
  const [items, onItemsChange] = useState([]);

  useEffect(() => {
    fetchData(page);
  }, [page]);

  const fetchData = async (pageIdx) => {
    const res = await fetch(
      `https://jsonplaceholder.typicode.com/todos?_limit=15&_page=${pageIdx}`
    ).then((r) => r.json());
    const resItems = res.map(({ title }) => ({
      label: title,
      value: title
    }));
    onItemsChange([...items, ...resItems]);
  };

  const loadOptions = () => items;

  // for search functionality use something like this:
  // const loadOptions = async (inputStr) => {
  //   const searchRes = await fetch(`${yourUrl}?search=${inputStr}`).then(r => r.json());
  //   return searchRes;
  // };

  const handleBottomScroll = () => {
    setPage((prevVal) => prevVal + 1);
  };

  return (
    <AsyncSelect
      cacheOptions
      isClearable={true}
      isSearchable={true}
      defaultOptions={items}
      onMenuScrollToBottom={handleBottomScroll}
      loadOptions={loadOptions}
    />
  );
};

export default WithPromises;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...