Stuck with Random Quote Machine

Tell us what’s happening:
Describe your issue in detail here.
I am doing the Random Quote Machine project and fetching random quotes from an api. I can either get a new quote and color with refresh button, or with the button, but not both. I can’t figure out what I am doing wrong.

Your code so far

import { useState, useEffect } from 'react'
import './App.css'

function App() {

  const back = '#ddd'
  const text = '#333'
  const colors = ['#edbefe', '#ffdfdf', '#bed0ef', '#e8c6ff', '#b5ffc8', '#eef093']

  let [quotes, setQuotes] = useState([{}])

  useEffect(() => {
    .then(response => response.json())
    .then(data => setQuotes(data.quotes))
  }, [])
  function randomColor() {
    return colors[Math.floor(Math.random() * colors.length)]

  function randomQuote() {
    return quotes[Math.floor(Math.random() * quotes.length)]

  let [color, setColor] = useState(randomColor())
  let [quote, setQuote] = useState(randomQuote())

  function change() {

  return (
    <div className="App w3-container w3-cursive" style={{ background: color, color: text }}>
      <div id="header" style={{ background: back, color: text }}>
        <div id="quote-text">

        <div id="quote-author">

      <div id="footer">
        <button id="share-tweet" style={{ background: back }}>
          share tweet

        <button id="new-quote" onClick={change} style={{ background: back }}>
          new quote


export default App;

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

Challenge: Build a Random Quote Machine

Link to the challenge:

Hello! Welcome to the community :partying_face:!

I was unable to understand this:

I can either get a new quote and color with refresh button, or with the button, but not both

You mean that you cannot get a new quote and color when you hit the refresh button on the browser? Could you explain it a little more :sweat_smile:.

The only problem I found is that you’re missing the React in the import line (which is required when using JSX):

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

With my present code the new quote is only generated when pressing the button . But when I refresh the browser window, no quote is given. When I changed the code for the refresh browser action to generate and view a new quote it would not do so when the button was pressed.

Ah! I see. You’re not setting the new quote/color the first time you fetch them. You could call change() right after setQuotes.

1 Like

Super, thank you very much!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.