When i click on nav button then table data loads but on second time click table data doesn't load but data in loads on every click in react js
I have put the code in componentdidMount() {}
to load it every time when it loads. i made async function which loads table and also set header.
{this.state.numofbugs.map((data)=> {
return (
<li key={data}>
<Link to={'/applogs/' + data}
className="waves-effect" className={this.props.location.pathname === '/applogs/' + data ? 'active': ''}>
<span className="font-size waves-effect" >{data}</span>
</Link>
</li>
)
})}
in file where it renders
componentDidMount() {
if (this.props.location.pathname.includes('app_')) {
this.showTable(this.props.location.pathname.split('/')[2]);
}
}
async showTable(col_name) {
// empty data
this.state.logtable = []
let conf = { headers: { Authorization: 'Bearer ' + localStorage.getItem('session') }}
Axios.get(links.baseURL + 'sample?collection=' + col_name, conf).then((response) => {
// get headers
this.state.tableHeaders = [
Object.keys(response.data.result[0])[0],
Object.keys(response.data.result[0])[1],
Object.keys(response.data.result[0])[2],
Object.keys(response.data.result[0])[3],
]
Object.keys(response.data.result).map((key) => {
this.state.logtable[key] = response.data.result[key];
this.state.logtable[key]['key'] = key.toString()
});
this.setState({'logtable': this.state.logtable});
});
}
I expected to get data in my table on every button click in table but after one time click on tab of collapse data laods in table then on second time data loads in tag not table
First thing, you don't need to empty your state like,
this.state.logtable = []
If you want to replace your existing state with new one, you can simply set the state with new data.
Another issue is, you are directly mutating your state, like this
this.state.tableHeaders = [
Object.keys(response.data.result[0])[0],
Object.keys(response.data.result[0])[1],
Object.keys(response.data.result[0])[2],
Object.keys(response.data.result[0])[3],
]
And this
Object.keys(response.data.result).map((key) => {
this.state.logtable[key] = response.data.result[key];
this.state.logtable[key]['key'] = key.toString()
});
You should make use of local variables to create temporary array, and then need to set them in your state like,
async showTable(col_name) {
let conf = { headers: { Authorization: 'Bearer ' + localStorage.getItem('session') }}
Axios.get(links.baseURL + 'sample?collection=' + col_name, conf).then((response) => {
// get headers
let tableHeaders = Object.keys(response.data.result[0]).map((key,index) => index <=3 && key.toString())
let logtable = Object.keys(response.data.result).map((key) => ({
logtable[key] : response.data.result[key];
logtable[key]['key'] : key.toString()
}));
this.setState({logtable, tableHeaders});
});
}