Random quote machine feedback and questions

Hello all, I just completed the Random Quote Machine project, not for the first, but for the first with “React Hooks”, which is something I want to learn to use.
Link:here

I have got 2 questions of my own about this project though:
1)when I made the version with hooks, the first quote I got upon loading the page is always the same one(index zero) from the array and I don’t immediately see how I could change this to be more random
2)To load my quotes i wrote:

<h1 id="text">{quotes.length>1? quotes[index].quote:''}</h1>

Where i work quotes.length. It works but I somehow doubt this is the best way to write that piece of code.

Any advice about these two things would be more than welcome, if there are other remarks, don’t hesitate to give them either.

Use two useEffect hooks (first effect runs once on initial render, and second after quotes gets updated):

  useEffect(() => {
    getQuotes(API);
  }, []);

  useEffect(() => {
    getIndex();
  }, [quotes]);

Not sure what exactly you don’t like about your code, but you could shorten it to:

<h1 id="text">{quotes[index]?.quote}</h1>
1 Like

Thank you for the two useEffect’s, that worked indeed.

About 2) I thought I could just work with “quotes ?” instead of “quotes.length>1?” but that gives me the error: “Type error: quotes[index] is undefined” so I changed it.
It’s not that I don’t like the code, it’s that I don’t fully understand why it has to be written this way.

It’s because initially quotes is an empty array and therefore quotes[0] is undefined and when you try to access quote of undefined you’ll get this error.