I am running into an issue with my app, which is a random quote generator. It’s supposed to work like this: The page starts off with a random quote and primary color, plus a Twitter URL is generated which the user can click allowing them to Tweet the quote. Click the “New Quote” and a new random color appears plus a new quote and corresponding Twitter URL. Here’s the code I have so far:
The problem is, the functions that control getting the new quote (getRandomQuote), the random color (getRandomColor) and the Twitter URL (getTwitterUrl) need to be in useEffect somehow, because when the page initially loads, I need to have a quote, color, and my Twitter URL, but if I put these functions in the dependancies array I create an infinite loop.
I guess I could just write out these functions inside of useEffect, but I still need to use those three functions (getRandomQuote, getPrimaryColor, getTwitterUrl) each time I click the “Get Quote” button and I can’t access my functions if they’re defined within another function. I feel like defining the same functions/constants twice would be a big no-no but I’m not really sure what else to do here. React is fairly new to me, and I’ve still got a lot to learn so I appreciate any and all help.
If you are replicating componentDidMount(), then you should not put anything in the dependency array - as you have it now. So, just do not put anything in there.
There should be no need to define a function twice. So, what is wrong with your code as it is now? The only thing I can see, which I do not understand is why you have handleClick within parentheses in the onClick callback?
Thanks for catching the parenthesis around the handleClick, that was a typo that I had missed, and also yes, I am trying to replicate a componentDidMount(). Besides that, I still receive the following error:
React Hook useEffect has missing dependencies: ‘getPrimaryColor’, ‘getRandomQuote’, and ‘getTwitterLink’. Either include them or remove the dependency array react-hooks/exhaustive-deps
You are welcome! I also encourage you NOT to ignore the dependencies error message. It is there in purpose. Try to find a solution and learn why it is happening. It is very important. Do not hesitate to contact me if you need help!