This type of error occur when you try to push data in array and you have not declare that variable as [] type .
Example :
image = ' ';
this.image.push({label:'testImage'});
The above code may give you following error .
![Solved ! [this.x.push is not a function] Type error](https://codersbugs.com/wp-content/uploads/2022/02/type-error.png)
The simplest way to solve this error is declare your with proper data type.
image = [];
this.image.push({label:'testImage'});
If you have found some another solution for the given issue then please post in comment section that may help other coders to save their time.
Why this error happens
push() is an array method. The error means the property you call it on is not an array at that moment. In the example above, image is set to a text string, and strings do not have a push method.
Correct code
// wrong: image is a string
// image = '';
// right: image is an array
images = [];
addImage() {
this.images = [...this.images, { label: 'testImage' }];
}The last version creates a new array each time. A plain field in LWC refreshes the screen only when you assign a new value, so push alone will not update the page unless the field uses @track.
Other causes of the same error
- Data from @wire or Apex is read only. Do not push into it directly. Copy it first with
this.items = [...data];. - The variable was overwritten. Another line may set it to an object, a string or null before push runs.
- Apex returned one record instead of a List. Check the return type of the method.
Quick check
console.log(Array.isArray(this.images), typeof this.images);If the first value is false, the variable is not an array, and you need to find where it gets its value.
FAQ
Why not use @track and push?
It works, but assigning a new array is simpler to read and works without the decorator.
Is the error different for frozen wire data?
Yes. You see a message such as Cannot add property, object is not extensible.