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

66
Views
Async function doesn't return in React app

I have an async function in a file (someFile.js) in my React app and I want the returned string from that function (someFunction) to be inserted in the webpage when it's finished. The problem is with the code below, I think the webpage loads before the promise is resolved, so the webpage appears blank. Can someone help me and see if there's a problem with my code below? The code below works when someFunction isn't an async function.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App.js';
import reportWebVitals from './reportWebVitals.js';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

App.js

import Header from "./components/Header.js";

function App() {
    return (
        <div className="container">
            <Header />
        </div>
    );
}

export default App;

Header.js

import someFunction from "./someFile.js";

const Header = () => {
    let text = someFunction();
    return (<h1>{text}</h1>)
}

export default Header;

someFile.js

const someFunction = async () => {
    let x = await someAsyncFunc();
    return x; //x is a string
}

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

0

Inside Header.js

import {useEffect,useState} from "react";
import someFunction from "./someFile.js";

const Header = () => {
      const [text, setText] = useState("");

  useEffect(() => {
    someFunction()
      .then((data) => setText(data))
      .catch((err) => console.log(err));
  }, []);

    return (<h1>{text}</h1>)
}

export default Header;
about 4 years ago · Juan Pablo Isaza Report

0

Remember the concept of immutability in React.js, you should do something like this:



import someFunction from "./someFile.js";


import { useState, useEffect, useCallback } from ‘react’;


const Header = () => {
   const [text, setText] = useState(‘’);

   const getApiText = useCallback(async () => {
     let apiReturnText = await someFunction();
     setText(apiReturnText);
   }, [])

    useEffect(() => {
      getApiText(); 
    }, [getApiText])

    return (<h1>{text}</h1>)
}

export default Header;
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!