const Table = ({ route, OnAccessBranch, Branche }) => {
let {Branches, Services, Guichets, items, colNames} = []
fetch("http://localhost:3000/GetTableData)
.then(response => response.json())
.then(Data => {
Branches = Data[0]
})
switch(route){
case "Branches":
items = Branches
colNames = Object.keys(Branches[0])
return (
<table className="f6 w-100 ml4 mt2 outline">
<thead>
<tr>
{
colNames.map((Colonnes, indexMetaData) => {
return(
<th className="fw6 bb b--black-20 pb3 pr3 bg-white tl" key={indexMetaData}>
{ Colonnes.toString().toUpperCase() }
</th>
)
})
}
</tr>
</thead>
<tbody className="lh-copy">
{
items.map((Ligne, indexRow) => {
return(
<tr key={indexRow}>
{
Object.entries(Ligne).map((Cell, indexCell) => {
return (
<td className="pv3 pr3 bb b--black-20" key={indexCell}> { Cell[1] }</td>
)
})
}
<td className="pv3 pr3 bb b--black-20">
<input type="button" value="Supprimer" name={items[indexRow].REF} className="white b pv2 ph3 bg-red hover-bg-mid-gray bn br2 hover-shadow-inner f3" />
</td>
<td className="pv3 pr3 bb b--black-20" id="Guichets">
<input onClick={OnAccessBranch} type="button" value="Guichets" id="Guichets" name={items[indexRow].REF} className="white b pv2 ph3 bg-blue hover-bg-mid-gray bn br2 hover-shadow-inner f3" />
</td>
<td className="pv3 pr3 bb b--black-20" id="Services">
<input onClick={OnAccessBranch} type="button" value="Services" id="Services" name={items[indexRow].REF} className="white b pv2 ph3 bg-green hover-bg-mid-gray bn br2 hover-shadow-inner f3" />
</td>
</tr>
)
})
}
</tbody>
</table>
)
So I have this React functional component that renders any given array of objects. The problem is in getting the table Data meaning the Branches variable must contain an array of objects but the fetch is executing after the switch clause which raises an undefined error since the Branches variable is still empty. Is there a way to load the data into the branches variable before executing the switch clause? PS: I tried putting the switch clause inside the fetch function then(Data => { switch.... }) but now the problem became that the component receive a promise object as a returned value.
You should use state for this. React will re-render the component (re-run the function) each time a state is updated. So this way the component will render once with branches
being undefined
and then once with branches
having the desired value, meaning you still have to take care of the case when branches
is undefined
(e.g. return a loading message).
const [branches, setBranches] = useState()
useEffect(() => {
fetch("http://localhost:3000/GetTableData")
.then(response => response.json())
.then(Data => {
setBranches(Data[0])
})
}, [])
Since the component renders multiple times we need to put it in a useEffect
to prevent the fetch from being run multiple times.