-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
  • 16,148
  • 4
  • 74
  • 121
caramel
  • 40
  • 6

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
  • 464
  • 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
  • 10,769
  • 1
  • 9
  • 29
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
  • 454
  • 4
  • 8
0

Try this

<button variant="dark" onClick={()=>deleteItem(product.id)} >Delete</button>
Yatrix
  • 12,794
  • 15
  • 42
  • 77
Sumit Pathak
  • 66
  • 1
  • 2