Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
How to render data returned from an asynchronous hook?

The code below is a simplified example of my problem. There is a lot more going on in the actual codebase, so let's just assume that my useHook function must be asynchronous and we cannot just fetch the data inside the useEffect hook.

It currently renders {}, but I want it to render "Data to be displayed"

const fetch = async () => {
  /* This code can't be changed */
  return "Data to be displayed"
}

const useFetch = async () => { // This function must be asynchronous
  let data = await fetch();
  return data;
};

const App = () =>  {
  const data = useFetch();
  const [state, setState] = useState(data);
  useEffect(() => {
    setState(data);
  }, [data]);
  return <h1>{JSON.stringify(state)}</h1>
}

export default App;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

change const data = useFetch(); to const data = await useFetch();

about 4 years ago · Juan Pablo Isaza Report

0

Move called inside the useEffect like this:

const App = () =>  {
 const [state, setState] = useState({});
 useEffect(() => {
    const fetchData = async () => {
        const data = await useFetch();
        setState(data);
    }
    fetchData()
 }, []);  // [] load first time
 return <h1>{JSON.stringify(state)}</h1>
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!