I have table in one form. after user submits the form data gets displayed in the result table. the problem is table header is getting displayed even before after user submit the form and data comes.
so I created one variable.
const [flag, setFlag] = useState(false)
I have set the flag as true after API call.
const { data } = await axios.get('http://localhost:3000/api/certificates', {
params: param,
});
setFlag(true); //Here changing the variable value to true.
setResponse(data);
}
and in table component div we are putting this flag
<div id="flag">
I also tried in table
component
<table className="table table-striped table-bordered " id="flag>
but none of them working. Could you please suggest on the same.
My requirement is table should be rendered only if API gets called and it has data.
CodePudding user response:
It should be like this in return section
Flag Check:-
return <div>
{flag &&
<table>
<tr>
<th>name</th>
<th>class</th>
</tr>
<table> }
</div>
data check:-
return <div>
{(response?.length > 0) &&
<table>
<tr>
<th>name</th>
<th>class</th>
</tr>
<table> }
</div>
we are using && (AND Operator) to check if flag is true then it show table otherwise not.
CodePudding user response:
Using if statement or conditional render should do it
if (data !== null && data.length > 0){ setFlag(true) } or when you render the content {data ?
: null }CodePudding user response:
const { data } = await axios.get('http://localhost:3000/api/certificates', {
params: param,
});
//add condition to check the length of data
if(data.length> 0){
setFlag(true); //Here changing the variable value to true.
setResponse(data);
} else {
setFlag(false);
setResponse(data);
}
}
in JSX use the flag as below
{flag?<table className="table table-striped table-bordered " id="flag">:null}
CodePudding user response:
let data = [];
axios.get('http://localhost:3000/api/certificates', {
params: param,
}).then(response=>{
data=response.data;
setFlag(true); //Here changing the variable value to true.
setResponse(data);
}).catch(err => {})