I am very new to react and after taking a course, I just wanted to do a project in react that I already did in Vue earlier just to practice React. But my useState is not updating the data that I want to list out.
The data from api is an array of Objects. End goal is to make a data table. So to be dynamic, I took the keys of the first object to take the column names. I used DataTable from 'react-data-table-component' for the data table. That didn't work. Now just to debug I thought to list out the column names but that didn't work either but it console logs.
I know this is something very basic and have searched lot of help in the internet and tried to solve who faced similar issue from lot of portals but nothing helped so far. Where am I doing wrong ?
import React, { useState, useEffect, Component } from 'react';
import axios from 'axios'
const tableData = () => {
const [tableData, setTableData] = useState([]);
const [columns, setColumns] = useState([])
useEffect(() => {
axios.get('http://localhost:4000/')
.then((res) => {
if (res.status === 200) {
if (res.data === 0) {
console.log("Something is wrong !!!");
} else {
const data = res.data['rows']
const columns = Object.keys(data[0])
console.log(columns)
setTableData(data)
setColumns(columns)
}
}
}).catch(error => {
console.log(error)
})
}, [])
return (
<div>
<ul>
{columns.map((columnName, index) => {
const {name} = columnName;
return (
<li key={index}>{ name }</li>
)
})}
</ul>
</div>
)
}