JS-React Random quote machine

Hello,
I am working on the project Random Quote Machine the problem that I have is “Cannot read property ‘author’ of undefined” I dont understand why it gives me this error on line 22 : console.log(onLoad().author); because if I write console.log(onLoad() I dont have any problem even when i refresh the page what i saw is that if I have my ( console.log(onLoad()) loaded on the page and after I use console.log(onLoad().author); it’s working but if I refresh the page I get the error.
If anyone can help me understand why this is happening please let me know :smile: THANKS!!!


import React, { useEffect, useState } from 'react';

import {random} from 'lodash';

import './App.css';

import Button from './components/Button';

function App() {

  const [fullQoute, setFullQoute] = useState([]);

  const [randomNumber, setRandomNumber] = useState(0);

 

  const getData = async () => {

    const response = await fetch('https://gist.githubusercontent.com/natebass/b0a548425a73bdf8ea5c618149fe1fce/raw/f4231cd5961f026264bb6bb3a6c41671b044f1f4/quotes.json');

    const data = await response.json();

    setFullQoute(data);

  }

  useEffect(() => {

    getData();

  }, []);

  const onLoad = () => {

    return fullQoute[random(0, fullQoute.length - 1)];

  }

  console.log(onLoad().author);

  return (

    <div className="App" id="quote-box">

      

      <Button clickHandler={() => setRandomNumber(random(0, fullQoute.length - 1))} buttonDisplayName="Next Quote" />

      

    </div>

  );

}

export default App;

hey @emilianmihainasaudea,

Im quessing this is due to console.log(onLoad().author); being called before your getData function has updated the fullQoute, try like this and see if you still get the error.

useEffect(() => {
    if(fullQoute.length > 0) {
     console.log(onLoad().author);
   }
}, [fullQoute.length])

by the way you have spelled quote wrong :slight_smile:

I try to do what you told me but it didn’t work. But a frind help me with the problem and got it solved.
Thanks you!