Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

API first returning undefined then gives data

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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([]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading