'Why is onEdit not being triggered?

Sorry if this is a silly issue/question, but I'm just starting off with AppsScript and it seems like there is something really simple I can't get right.

I'm trying to sort a spreadsheet based on the below function:

    const row = e.range.getRow()
    const column = e.range.getColumn()
    const ss = e.source
    const currentSheet =  ss.getActiveSheet()
    const getSheetName = currentSheet.getSheetName() 

    if(!(currentSheetName === "UPDATE" && column === 5 && row >= 2)) return
   
    const range = currentSheet.getRange(2,1,currentSheet.getLastRow()-1,5)

    range.sort({column: 5, ascending: false})

}


function onEdit(e){

  autoSort(e)

}

Which gives me the following error: TypeError: Cannot read property 'range' of undefined

Is there something I need to activate before being able to use trigger events? I'm really unsure about what I'm missing. Is there anything wrong with the code that you can spot?



Solution 1:[1]

This is an example that is working, you can take it as an example for your script:

function autoSort(e) {
  const { range, source } = e
  const sheetName = source.getActiveSheet().getSheetName()
  const row = range.getRow()
  const column = range.getColumn()
  const data = {
    sheetName,
    row,
    column
  }
  source.getActiveSheet().getRange('A1').setValue(
    JSON.stringify(data, null, 2)
  )
}

function onEdit(e) {
  autoSort(e)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1