Reactjs " Class constructor upload cannot be invoked without 'new'

Im trying to activate a function with reactjs
But i keep getting the same error:

Uncaught TypeError: Class constructor Upload cannot be invoked without ‘new’

i dont know what to do with it:

import React, { Component } from 'react';

export class Upload extends Component {
    static displayName = Upload.name;

    constructor(props) {
        super(props);
        this.state = {
            Title: "empty",
            Price: 1,
            Description: "empty description",
            quantity: 2,
            loading: true
        };
    }

Upload = () =>{

    const item =
    {
        title: this.state.Title,
        price: this.state.Price,
        description: this.state.Description,
        quantity: this.state.quantity
    };
        fetch('api/Upload', {
            method: 'POST',
            body: JSON.stringify(item)
        }).then(response => response.json())
            .then(data => console.log('succes', data))
        .catch(error => console.error("unable to achive this", error))
    }

render() {
    return (
            <div>
            <h1>Upload here</h1>
            <button id="uploadbutton" onClick={ Upload }>Upload the product</button>
            </div>
            );
    }
}

Your react component’s name is Upload, your function’s name is also Upload, in javascript you don’t start with capitals when you name variables and functions.

<button id=“uploadbutton” onClick={ Upload }>

1 Like

Understood, Thank you ,

Now it has problems reading the item const
I am used to javascript, Hopefully you can help me with this one:
it is saying: Uncaught TypeError: Cannot read property ‘state’ of undefined

and showing the following code:

      const item =
        {
            title: this.state.Title,
            price: this.state.Price,
            description: this.state.Description,
            quantity: this.state.quantity
        };

Can you please post the full updated component code?

You need to bind your function inside your constructor:

this.uploadFunction = this.uploadFunction.bind(this);

@ozanbaskan They are using the Class Properties syntax for the method. So binding shouldn’t be needed.


I would suggest you post your current component code in full.

Edit: I do not seeing you using this for the click handler, BTW. (onClick={this.uploadFn})

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.