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;
useEffect
to render the result of an async function.