'await function returns a promise and returns true even if the condition is false | React Functional Component
In my JSX file, I have a function like this.
async isPresent () {
const res = await AsyncFunction();
if (res) {
return true;
}
return false;
}
and then using it in a conditional rendering as
{ this.isPresent() && <div> Content </div> }
But this always returns true.
How do I solve this?
Solution 1:[1]
You cannot have asynchronous logic in render. You need to extract the present boolean into a state and make the asynchronous call inside something like componentDidMount and then update the present state from there.
Refer to the example below:
const sleep = (delay) => new Promise(res => setTimeout(() => res(true), delay))
class App extends React.Component {
constructor() {
super();
this.state = {
present: false,
};
}
componentDidMount() {
sleep(1000).then((res) => {
if (res) {
this.setState({ present: true });
}
});
}
render() {
return <div>{this.state.present ? "Present": "Not Present"}</div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SSM |
