Reputation: 15
i am working on a project with a react.js FE, a Node/Express.js BE and a database. I am currently working on a function which trigger my delete Route in BE. But my function trigger with every load and onlick, but should only trigger onClick.
Here are code samples of my service and my FE component. I am new to react.js so help would be apprechiated.
hardwareService.js:
static deleteHardware(hardwareId) {
console.log(hardwareId);
return axios.delete(hostname + '/hardware/' + hardwareId)
.then(response => {
return response;
})
}
component:
deleteOnClick = (id) => {
console.log('handleDelete wird ausgeführt!' + id);
HardwareService.deleteHardware(id);
}
html:
<tbody>
{this.state.hardware.map(hardware => (
<tr key={hardware.id}>
<td>{hardware.id}</td>
<td>{hardware.producer}</td>
<td>{hardware.model}</td>
<td>{hardware.type}</td>
<td>{hardware.serial_number}</td>
<td>{hardware.price}</td>
<td>{<Button variant="primary">Bearbeiten</Button>}</td>
<td>{<Button variant="primary" onClick=
{this.deleteOnClick(hardware.id)}>Löschen</Button>}</td>
</tr>
))}
</tbody>
Upvotes: 1
Views: 91
Reputation: 31815
Replace this line:
onClick={this.deleteOnClick(hardware.id)}>Löschen</Button>}
With this:
onClick={() => this.deleteOnClick(hardware.id)}>Löschen</Button>}
Explanation: in your current code you are calling the function immediately (when rendering the component) then passing the result as an event handler which has no effect. So you need to encapsulate the function call in another function for future call (arrow functions are well suited for that).
The hardware.id
parameter will be enclosed in that function thanks to the JavaScript closure mechanism.
Upvotes: 2