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.
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();
import Header from "./components/Header.js";
function App() {
return (
<div className="container">
<Header />
</div>
);
}
export default App;
import someFunction from "./someFile.js";
const Header = () => {
let text = someFunction();
return (<h1>{text}</h1>)
}
export default Header;
const someFunction = async () => {
let x = await someAsyncFunc();
return x; //x is a string
}
export default someFunction;
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;
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;