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>
)
}
>Solution :
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([]);