Function returning 'undefined'

Hello, going through ‘Front End Libraries Projects’ and I’m currently on ‘Build A Random Quote Machine

I currently have a .JSON file to hold the quote data, I then define a function ‘getQuote’ that reads the JSON file and returns a random quote+author. My issue is when I import and use the function within a react function component the function suddenly only returns ‘undefined’. I’m not really sure why and I think it’s to do with scope.

If you’d like to see the full project, i’ve made a git repo:

Also, here’s the main code:


import quoteData from './quotes'

const getQuote = () => {
    const randomNum = Math.floor(Math.random() * Math.floor(quoteData['quotes'].length));
    // console.log(randomNum);
    // console.log(quoteData['quotes'][randomNum]);
    return quoteData['quotes'][randomNum][1];

export default getQuote;


import React, { useState, useEffect } from 'react';
import './styles/App.scss';
import ReactFCCtest from 'react-fcctest';
import getQuote from './utils/quoteHandler'

const QuoteBox = (props) => {

  const handleClick = () => {
    props.quote = getQuote();

  return (
    <div id="quote-box">

      <blockquote className='blockquote'>
        <p id='text'>
        <footer className='blockquote-footer' id="author">

      <button id='new-quote' className='btn btn-primary' onClick={handleClick}>New Quote!</button>
      <button id='tweet-quote'></button>

const App = () => {
  const [quote, setQuote] = useState(getQuote());

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

  return (
      <ReactFCCtest />
      <QuoteBox id='quote-box' quote={quote} />

export default App;

Any help is appreciated :slight_smile: thanks!

return quoteData['quotes'][randomNum] looks like it returns an object but you’re trying to access the index of an array.

So you should be able to replace [1] with .quoteText or [‘quoteText’].

1 Like

Oh I see! Thank you so much