I have 2 components, A and B. A passes 2 data points to B through props, and inside B I am using these props to make an API call. However this throws an error: "TypeError: data.forEach is not a function". Once the error message is displayed in the console, the results which are supposed to be populated in the react table also get logged, after few moments. I am not able to understand where I am going wrong. Any help is appreciated!
const TableT = (props) => {
const [data, setData] = useState([])
async function fetchTableData(t, d){
await Aios.get("http://localhost:4000/api?dataset="+d+"/table="+t).then((res) => {
console.log(res.data)
return res.data
})
}
useEffect(() => {
let d = fetchTableData(props.dataset, props.table)
setData(d)
}, [data])
//Here comes the standard code of react table, rendered using the "data" state
}
My belief is that the table is getting rendered before we have the data through the API call, hence the error(I could be wrong). Happy to clarify anything if needed!
http:localhosttohttp://localhost? That assumesAiosis the correct variable name for your axios lib. There are other problems with your code to be sure, but that's where I would start.http://localhostonly. And Aios is the correct variable name. I am getting the response from API, but the data is getting logged only after the error is logged.let d = fetchTableData(props.dataset, props.table)won't get anything back because thefetchTableDatafunction doesn't return anything. Try testing it by puttingconsole.log(d);right beforesetData(d). I bet you will get a promise back, which is not what you expect.