Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
React-Table & React-Query getting TypeError: Cannot read property 'forEach' of undefined

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

  • fallback to an empty array when passing to react-table: data: compras ?? []
  • destruct a default value: const { data: compras = [] } = useQuery(…)
  • Pass placeholderData to useQuery
  • Pass initialData to useQuery
  • Check for isLoading 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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!