Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useMemo with an external API?

I'm working with react-table library for filtering and pagination. I am requesting data from a custom API using Node and rendering it using useTable hook from react-table. The documentation for react-table says the table data should be memoized, so I use the useMemo hook. The code is as shown:

  const data = React.useMemo(() => {
    axios.get("/custom/api/endpoint")
      .then((res) => {
        return res.data;   //Returns an array of objects
      })
      .catch((err) => {
        console.log("err");
      });
  }, []);

However, I am getting the following error:

Uncaught TypeError: Cannot read property 'forEach' of undefined
    at accessRowsForColumn (useTable.js:591)
    at useTable.js:195
    .
    .

Can anyone help me figure this? Thanks in advance!

like image 818
yksolanki9 Avatar asked Oct 29 '25 07:10

yksolanki9


1 Answers

You are memoizing the promise that axios creates. Instead make the call with useEffect(), and set the state. Unless you'll set the state again, the data would not change:

const [data, setData] = useState([]); // use an empty array as initial value

useEffect(() => {
  axios.get("/custom/api/endpoint")
    .then((res) => {
      setData(res.data); // set the state
    })
    .catch((err) => {
      console.log("err");
    });
}, []);
like image 178
Ori Drori Avatar answered Oct 31 '25 12:10

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!