Running into an issue where I have an "if statement" that is displaying the else portion of the statement for about half a second before actually matching the first part of the statement. How can I get it to only display what it matches?
For example, the first part of the if statement and avoid ever showing the else condition of the if statement. In the case of the code below when the browser loads the component it shows "This is not a Technical report" for about half a second then it goes away and "This is a Technical report" appears. When done the other way the first part of the if statement never appears and only the else section appears. This issue only happens if the first condition matches. Code Below:
import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";
import { useParams } from "react-router-dom";
function ViewReport(props) {
if (Report.InterviewType === "Technical") {
return (
<div>
<h1>This is a Technical report</h1>
</div>
);
} else {
return (
<div>
<h1>This is not a Technical report</h1>
</div>
);
}
}
export default ViewReport;
CodePudding user response:
This happens because initially, it takes sometime to load Report
object and as a result, if
condition fails. Therefore, you can check whether Report.InterviewType
does exist.
import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";
import { useParams } from "react-router-dom";
function ViewReport(props) {
if (Report.InterviewType === "Technical") {
return (
<div>
<h1>This is a Technical report</h1>
</div>
);
} else if(Report.InterviewType) {
return (
<div>
<h1>This is not a Technical report</h1>
</div>
);
}
}
export default ViewReport;
In this case, I believe that initial value of Report.InterviewType
is undefined
or null
. If it's not null, then you have to put the relevant initial value for else if
check. Let's say the initial value is x
, then it will be as follows.
else if(Report.InterviewType === x){ ... }
CodePudding user response:
Thanks to @kavinduvlndika and @junaidfaryad I was able to understand why the issue was occurring and I simply added an empty return as a third condition in the if statement. This allows a staging point while the API fetches the data.
import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";
import { useParams } from "react-router-dom";
function ViewReport(props) {
if (Report.InterviewType === "Technical") {
return (
<div>
<h1>This is a Technical Interview</h1>
</div>
);
} else if (Report.InterviewType === "LeadershipPrinciples") {
return (
<div>
<h1>This is not a Technical Interview</h1>
</div>
);
} else {
return <div></div>;
}
}