Reputation: 152
Team any better way to get data from Axios API and then use it in the same function as data.
import React, { Component, useState, useMemo } from 'react';
import { useTable } from 'react-table';
import { COLUMNS } from './columns';
import axios from 'axios';
export const BasicTable = () => {
const [myresponse, setmyresponse] =useState([]);
axios.get('http://localhost:5001/inventory/cluster/cluster1/servertype/test1')
.then((response) => {
const myresponse= response.data;
setmyresponse(myresponse)
});
const columns = useMemo(() => COLUMNS, [])
const data = useMemo(() => myresponse,[])
const tableInstance = useTable({
columns: columns,
data: data
})
const { getTableProps,getTableBodyProps, headerGroups,rows,prepareRow } =tableInstance
return(
<table {...getTableProps()}>
<thead >
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{
headerGroup.headers.map(column =>(
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{
rows.map(row => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{
row.cells.map(cell =>{
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})
}
</tr>
)
})
}
</tbody>
</table>
)
};
What's happening right now, is I get data using console.log but the requests keep running indefinitely to my Axios API. Any thoughts on what am doing wrong?
Upvotes: 1
Views: 680
Reputation: 7156
Just do this: I have used useEffect
so that your API gets called only once after your component did mount.
useEffect(() => {
axios
.get('http://localhost:5001/inventory/cluster/cluster1/servertype/test1')
.then((response) => {
const myresponse= response.data;
setmyresponse(myresponse)
});
}, [])
const columns = useMemo(() => COLUMNS, [])
const data = useMemo(() => myresponse,[myresponse])
const tableInstance = useTable({
columns: columns,
data: data
});
Upvotes: 2