Front End Development Libraries Projects - Build a Random Quote Machine

Tell us what’s happening:

I am trying to get quote data from an API using fetch in my class component, but when I try to display the data, it doesn’t display and I get in the console undefined. I guess when fetch is receiving the data, the component renders first, then the data gets received after. How do I account for this?

Your code so far

import React from 'react';
import './styles.css';

class QuoteMachine extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            quote: this.fetchQuote()
        }
        this.fetchQuote = this.fetchQuote.bind(this);
    }

    fetchQuote(){
        let resultData = [];
        fetch('https://type.fit/api/quotes')
            .then((res)=>res.json())
            .then((data)=>{
                resultData = data;
                console.log(resultData[0].text);
                console.log(resultData);
                return resultData[0].text;
            })
        
        // return resultData;
    }

    render(){
        let quotesData = this.fetchQuote();
        console.log("Line 29: quotesData result:", quotesData);
        // console.log("Test quotesData: ", quotesData[0][text]);
        return (
            <div>
                <h1>TEST TEST TEST 3</h1>
                <div id="quote-box">
                    <div id="text">
                        <p>"Quote placeholder: {this.state.quote}"</p>
                    </div>
                    <div id="author">
                        <p>- Author Placeholder 2</p>
                    </div>
                    <i className="bi bi-twitter-x"></i>
                    <button id="new-quote" className='btn btn-dark'>New Quote</button>
                    
                </div>
            </div>
        );
    }
}

const App = ()=>{
    return (
        <div>
            <QuoteMachine />
        </div>
    );
}
export default App;

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36

Challenge Information:

Front End Development Libraries Projects - Build a Random Quote Machine

1 Like

I figured it out. I had to call fetch API in a componentDidMount() method.

1 Like