Reputation: 23
Upon calling api it returns undefined then gives the data. I'm calling getData function in useEffect, but it returns undefined followed by the data. I want it to just give the data. Help me!
const Table = () => {
const [pageSize, setPageSize] = useState(10);
const [tableData, setTableData] = useState();
useEffect(() => {
getData()
}, [])
const getData = async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/users').catch(err => console.log(err))
if(response) {
const result = response.data
setTableData(result)
}
}
console.log(tableData)
const activeColumn = [
{field: 'action', headerName: 'Action', width: 200, renderCell:() => {
return(
<div className='cellAction'>
<div className='viewButton'>View</div>
<div className='deleteButton'>Delete</div>
</div>
)
}}
]
return (
<div className='table'>
<DataGrid
rows={tableData}
columns={columnData.concat(activeColumn)}
pageSize={pageSize}
onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
rowsPerPageOptions={[5, 10, 25, 50, 100]}
checkboxSelection
/>
</div>
)
}
Upvotes: 0
Views: 1766
Reputation: 625
Tested your api route in browser directly
Then it is not your api route return undefined
.
It is because your tableData is undefined
when creating the Table
component.
const [tableData, setTableData] = useState();
Give a default value (like empty array => useState([])
) or just add a check in your return()
like this
return (
<div className='table'>
// 📌 render if tableData is not undefined
{ tableData && <DataGrid
rows={tableData}
columns={columnData.concat(activeColumn)}
pageSize={pageSize}
onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
rowsPerPageOptions={[5, 10, 25, 50, 100]}
checkboxSelection
/>
}
</div>
)
Upvotes: -1
Reputation: 785
your api call does not return undefined. the api call is an async function so when you call it the setTableData wont be called till the data comes from server and the tableData will be its default value which is undefined to avoid errors you can set its default value as an empty array by doing this
const [tableData, setTableData] = useState([]);
Upvotes: 2
Reputation: 144
The reason why its getting undefined is because tableData
does not have a default value.
Upvotes: 1