1

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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately all of these result in a hydration error from next.js...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.