0

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>
  )
}
deoxzy
  • 23
  • 3
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – CherryDT Oct 11 '22 at 07:24

3 Answers3

2

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([]);
1

The reason why its getting undefined is because tableData does not have a default value.

-1

Tested your api route in browser directly
enter image description here

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>
  )
HsuTingHuan
  • 615
  • 1
  • 7
  • 23