-1

I created a functional component in which i get data from Django REST and I want to manage deleting items. When I write a proper function I get the error

Cannot read property 'deleteItem' of undefined

I guess it is because I don't have a constructor here, am I right?

This is my function:

  function deleteItem(id) {
    axios.delete('http://127.0.0.1:8000/api/products' + `/${id}/`);
};

And I want to use it here:

<Button variant="dark" onClick={()=>this.deleteItem(product.id)} >Delete</Button>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
caramel
  • 60
  • 8

5 Answers5

2

if it's a functional component then you don't have this. You can achieve what you want in a functional component like this

function myComponent(){

  const deleteItem = (id) => {
    axios.delete('http://127.0.0.1:8000/api/products' + `/${id}/`);
  };

  return <Button variant="dark" onClick={()=> () => deleteItem(product.id)} >Delete</Button>
}

sazzad
  • 505
  • 4
  • 5
2

In functions, this depends on how the method is executed. Yours is a function that runs like this:

App()

There is no object on which this method is run.

When not found this belongs to the global object/window(in case of browsers). Thing to note is that react runs in strict mode. So this is undefined.

You could simply use deleteMethod().

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

Constructor is a class concept, constructor is a method called when a class is instantiated. Thus functions have no constructors only classes do

0

concept of this refers to a pointer to methods and attributes in class components that you can access them by that, so you are not capable of use that in functional components , you are able to try followings this:

const MyComponent = (props) => {

    //...

    function deleteItem(id) {
        axios.delete('http://127.0.0.1:8000/api/products' + `/${id}/`);
    };

    return <Button variant="dark" onClick={()=> deleteItem(product.id)} >Delete</Button>
};
MHP
  • 577
  • 5
  • 9
0

Try this

<button variant="dark" onClick={()=>deleteItem(product.id)} >Delete</button>
Yatrix
  • 13,361
  • 16
  • 48
  • 78
Sumit Pathak
  • 86
  • 1
  • 2