Initiate function on page load
That is because when you're calling fetchData()
in useEffect
, no argument is being provided to the function. Yet in the function you are expecting the first argument to be present and calling it with e.preventDefault()
. Since e
will be undefined, attempting to access a key/property inside undefined
will throw an error.
There are two solutions:
- Only invoke functions stored in
e
when it is not undefined - Write a separate handler for the click event binding
Solution 1: Use optional chaining
By first checking if e
is null or undefined, we can prevent attempting to access a key/property on it:
function fetchData(e) {
e?.preventDefault();
// Additional fetching logic
}
If you want to also support browsers that do not support optional chaining, then using the logical AND operand (&&
) to perform lazy evaluation / short-circuiting will also work:
function fetchData(e) {
e && e.preventDefault();
// Additional fetching logic
}
Solution 2: Separate event handlers for button
Remove e
from your fetchData function completely:
function fetchData() {
// Additional fetching logic
}
...and prevent the default event at the level of the click handler:
const onClick = (e) => {
e.preventDefault();
fetchData();
}
<button type="button" onClick={onClick}>Get data</button>