简体   繁体   中英

Why does my UseState hook keeps on failing?

I want to use UseState hook for updating data in my Table component. The data to be used in the Table component is fetched by another function which is imported paginationForDataAdded .

Its look like stackoverflow due to re-rendering. setAllData(searchResults); will re-render the component and again make api call and repated.

right way to call API.

 const [allData, setAllData] = useState([]);

useEffect(function () {
  const {
    searchResults,
    furnishedData,
    entitledData
  } = paginationForDataAdded({
    searchFunction: search,
    collectionsData: collections
  });
  setAllData(searchResults);
});

Assuming paginationForDataAdded is a function that returns a Promise which resolves with an object that looks like the following:

{ 
  searchResults: { resultarray: [...] }, 
  furnishedData: [...], 
  entitledData: [...] 
}

You should do the following your in component:

function App(props) {
  const [allData, setAllData] = React.useState([]);
  // ...

  React.useEffect(() => {
    paginationForDataAdded({
      searchFunction: search,
      collectionsData: collections,
    })
    .then(
      ({ searchResults, furnishedData, entitledData }) => {
        const nextAllData = searchResults.resultarray || [];
        setAllData(nextAllData);
      }
    )
    .catch(/* handle errors appropriately */);

    // an empty dependency array so that this hooks runs
    // only once when the component renders for the first time
  }, [])

  return (
    <Table 
      id="pop-table"
      data={allData}
      tableColumns={[...]}
    />
  );
}

However, if paginationForDataAdded is not an asynchronous call, then you should do the following:

function App(props) {
  const [allData, setAllData] = React.useState([]);
  // ...

  React.useEffect(() => {
    const {
      searchResults,
      furnishedData,
      entitledData,
    } = paginationForDataAdded({
      searchFunction: search,
      collectionsData: collections
    });
    const nextAllData = searchResults.resultarray || [];
    setAllData(nextAllData)

    // an empty dependency array so that this hooks runs
    // only once when the component renders for the first time
  }, [])

  return (
    <Table 
      id="pop-table"
      data={allData}
      tableColumns={[...]}
    />
  );
}

Hope this helps.

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