I am using react-query to fetch data into react-table, but everytime I get the "TypeError: Cannot read property 'forEach' of undefined" error. The only way I can fix it is using "data" into the react-query "initialData" option, is there another way to fix this error?
const TableCompras = () => {
const data = [
{
nf: null,
fornecedor: null,
pagamento: null,
valorTotal: null
}
];
// Fetch Compras
const { data: compras, error, isLoading } = useQuery(
"compras", getAllCompras
, {
initialData: data
}
);
// React Table
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
pageOptions,
prepareRow,
state,
setGlobalFilter
} = useTable(
{
columns,
data: compras,
initialState: { pageSize: 5 }
},
useGlobalFilter,
useSortBy,
usePagination
);
}
Since react-query gets data asynchronously from somewhere, data is undefined on the first run until your network request actually returns the data. Apparently, you cannot pass undefined to react-table, so you can:
data: compras ?? []const { data: compras = [] } = useQuery(…)placeholderData to useQueryinitialData to useQueryisLoading returned from useQuery, move the table to a separate component and don’t render that component as long as you are loading (e.g. render a loading spinner instead)