deoxzy
deoxzy

Reputation: 23

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>
  )
}

Upvotes: 0

Views: 1766

Answers (3)

HsuTingHuan
HsuTingHuan

Reputation: 625

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>
  )

Upvotes: -1

abolfazl shamsollahi
abolfazl shamsollahi

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

Stephen Asuncion
Stephen Asuncion

Reputation: 144

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

Upvotes: 1

Related Questions