Nhan Nguyen
Nhan Nguyen

Reputation: 405

Unhandled Rejection (TypeError): Invalid attempt to spread non-iterable instance how can I fix

I am having error like this in my project:

Unhandled Rejection (TypeError): Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method

Here is my SortContracts.ts code:

function sortContracts(
  contracts: ContractUsage[],
  sortField?: SortType,
  sortDirection?: SortDirection
): any[] {
  let sortFunction:any
  switch (sortField) {
    // Sort by End Date
    case SortType.DATE_SORT:
      if (sortDirection === SortDirection.ASC) {
        // Sort by End Date ASC
        sortFunction = (a:any, b:any) => endDateSortAscFunc(a, b);
      } else {
        // Sort by End Date DESC
        sortFunction = (a:any, b:any) => endDateSortDescFunc(a, b);
      }
      break;

    // Sort by ContractID
    case SortType.CONTRACT_SORT:
      if (sortDirection === SortDirection.ASC) {
        // Sort by ContractID ASC
        sortFunction = (a:any, b:any) => contractIdSortAscFunc(a, b);
      } else {
        // Sort by ContractID DESC
        sortFunction = (a:any, b:any) => contractIdSortDescFunc(a, b);
      }
      break;

    case SortType.USAGE_ORDER:
      if (sortDirection === SortDirection.ASC) {
        sortFunction = (a:any, b:any) => usageOrderSortAscFunc(a, b);
      } else {
        sortFunction = (a:any, b:any) => usageOrderSortDescFunc(a, b);
      }
      break;
    // default sort
    default:
      sortFunction = (a:any, b:any) => contractIdSortAscFunc(a, b);
  }

  // Return the sorted contracts
  console.log('contract here: ',  [...contracts].sort(sortFunction))
  return [...contracts].sort(sortFunction);
}

enter image description here

Upvotes: 0

Views: 5691

Answers (1)

bobkorinek
bobkorinek

Reputation: 685

The variable you are trying to spread (ie. [...contracts]) is not iterable. If you want use this operator, you need to have this variable iterable. Check the variable if it is really an array (or any other iterable type) and if it's not null or undefined.

Upvotes: 1

Related Questions