createCodeCell from an extension

I am developing an extension including a little function that could create a code cell from the widget. I am trying to use the

const nbContent = this.notebookTracker.currentWidget?.content;
const codeCell = nbContent.contentFactory.createCodeCell({
  cell: {
    cell_type: 'code',
    source: ['some code line 1', 'some code line 2'],
    metadata: {}
  }
});
const cells = nbContent.model.cells;
cells.insert(cells.length, codeCell);

But having an error. When I console.log(‘New Cell:’, codeCell), it says cannot read ‘metadataChanged’. I guess there is something wrong in the createCodeCell options. Does anyone have any ideas?

I’m also struggling with creating non-empty cells from an extension. I’d love a working example.

You can try NotebookActions.insertBelow

Thanks Wengxi! In the end, rather than use NotebookActions, I instead deleted the cell and inserted a new one.

 const markdownCell = {
    cell_type: 'markdown',
    metadata: {},
    source: markdownMessage,
    trusted: true,
  };
  const codeCell = {
    cell_type: 'code',
    metadata: {},
    source: code,
    trusted: true,
  };
// model is a instance of INotebookModel
model.sharedModel.insertCells(cellCount - 1, [markdownCell, codeCell]);