Invalid Hook Call with Async API Call

Viewed 527

I am trying to use a react hook like useMemo or useEffect inside my functional component. The API call is async, and I think that may be what's causing the error.

Service file:

export const getData = (): wretch =>
  fetch('/d/get_data')
    .get()
    .json();

Data formatting logic file:

import {getData} from './services';

export const formatData = (onClick, onSort) => {
  // logic here - omitted
  const formattedData = [];
  return getData().then(res => {
    res.forEach( 
      // more data formatting logic
    )
    return {formattedData: formattedData, originalData: res};
})};

Rendering file:

import {formatData} from './formatData';

const MyTable = () => {
  useEffect(() => formatData({onClick: handleClick, onSort: handleSort}).then(res => setData(res)), []);

Error message:

enter image description here

2 Answers

You're correct about the part where you cant have async code in your useEffect. A workaroud for that is similar to what you're doing.

useEffect(() => {

  async function myfunc(){
    // Do async work
    const response = await apiCall();
    setData(response);

  }
  myFunc();
},[]) 

This might not answer your question, but it is a common pattern you might find useful :)

Please try this one.

const MyTable = () => {
  useEffect(async () => {
    const data = await formatData({onClick: handleClick, onSort: handleSort});
    setData(data);
  },
  []);
}
Related