I fixed a bug I had, but I'm not sure what specifically was wrong, or particularly what about it was going wrong. Below is the code before it started behaving.
This code caused the function to run every time the page re-rendered (which was a lot!). Here's the specific component that's getting called:
export const GetDBCards = () => {
const fetchDBCards = () => {
fetch('http://localhost:3001/users')
.then(res => res.json())
.then(json => console.log(json))
}
return(
<>
<button onClick={fetchDBCards()}>Get Cards</button>
</>
)
}
The only change was editing the actual function call in onClick to remove the parenthesis. My current (and expectantly) functional code for the line is this
<button onClick={fetchDBCards}> Get Cards</button>
What am I misunderstanding about the function call including the parenthetical?
CodePudding user response:
By including the parenthesis, you are calling the function during render, this means that you’re unconditionally executing it every times the component render. Instead you should pass the reference to the function and call it later on.
//