How can I use e.preventDefault() with multiple Parameters? I'm getting the error:
TypeError: Cannot read properties of undefined (reading 'preventDefault')
With this code:
import React, { useState, useEffect } from "react";
import './App.css';
import axios from './axios.js';
const removeCustomer = (id) => {
axios.get(`/customers/delete/${id}`)
window.location = "/"
}
function addCustomer(name, address, e){
e.preventDefault();
console.log("hello");
}
function App() {
const [customers, setCustomers] = useState([])
const [name, setName] = useState("")
const [address, setAddress] = useState("")
useEffect(() => {
async function fetchData() {
const req = await axios.get("/customers");
setCustomers(req.data);
}
fetchData();
}, [])
return (
<>
<h1 className="title">All Customers</h1>
<div className="customers">
{customers.map((customer) => (
<div onClick={() => {
removeCustomer(customer.id)
}} key={customer.id} className="customer">
<h3>{customer.name}</h3>
<p>{customer.address}</p>
</div>
))}
</div>
<form>
<input type="text" placeholder="Name" onChange={(e) => setName(e.target.value)}/>
<input type="text" placeholder="Address" onChange={(e) => setAddress(e.target.value)}/>
<button type="submit" onClick={() => addCustomer(name, address)}>Add</button>
</form>
</>
);
}
export default App;
I have one question (don't worry if you don't answer it) how can I send the two variables name and address to my backend?
You are expecting the event to come from where you are calling the function. But you are calling the function with an arrow function. You need to pass the event to function when you perform a click.
// Your js Code will be like this
function addCustomer(name, address, e){
e.preventDefault();
console.log("hello");
}
// Your HTML code will be like this
<button type="submit" onClick={(e) => addCustomer(name, address, e)}>Add</button>
This should definitely work.