I am filling a datatable to display on my webpage. It only renders when I interact with the sort button. Where should I fill this array for use in a datatable such that it happens before the rendering?
export function MyComponent() {
const columns = [
{
name: 'Player',
selector: row => row.Player,
sortable: true,
},
];
const [teamArray, setTeamArray] = useState([])
const [managerTeamList, setTeamList] = useState([])
const [bootstrapData, setBootstrapData] = useState([])
var managersteam = [];
useEffect(() => {
getBootstrap().then(bootstrap => {
setBootstrapData(bootstrap.elements)
})
getManagersTeam(27356,28).then(data => {
setTeamList(data.picks)
})
for (var i in managerTeamList) {
for (var j in bootstrapData) {
if (managerTeamList[i].element == bootstrapData[j].id) {
managersteam.push({
"Player" : bootstrapData[j].second_name
})
break;
}
}
}
setTeamArray(managersteam)
}, []);
return (
<DataTable columns={columns} data={teamArray}/>
)
}
CodePudding user response:
Please know that the api requests are asynchronous - getBootstrap
and getManagersTeam
- so they are empty when you try to loop through the data.
You can use async/await or just update the teamArray when the promises are solved.
You can use the below code:
export function MyComponent() {
const columns = [
{
name: "Player",
selector: (row) => row.Player,
sortable: true,
},
];
const [teamArray, setTeamArray] = useState([]);
const fetchData = async () => {
var managersteam = [];
const [bootstrap, data] = await Promise.all([
getBootstrap(),
getManagersTeam(27356, 28)
]);
for (var i in data.picks) {
for (var j in bootstrap.elements) {
if (data.picks[i].element == bootstrap.elements[j].id) {
managersteam.push({
Player: bootstrap.elements[j].second_name,
});
break;
}
}
}
setTeamArray(managersteam);
}
useEffect(() => {
fetchData();
}, []);
return <DataTable columns={columns} data={teamArray} />;
}