Random quote generator using react

I want to include a button element in my react component that brings a new random qoute every time it’s clicked but I am currently stuck because the button just won’t work. What should I change or what am I doing wrong. I am new to react and this is my first challenge

  constructor(props) {
    super(props);
    this.state = { qoute: "", randomQoute: "" };
    this.newQoute = this.newQoute.bind(this);
  }
  async componentDidMount() {
    let response = await fetch("https://type.fit/api/quotes");
    let data = await response.json();
    this.setState({ qoute: data });
    let randomIndex = Math.floor(Math.random() * data.length);
    this.setState({ randomQoute: data[randomIndex] });
  }
//this is function that is called every time the button is clicked 
  newQoute() {
    let randomIndex = Math.floor(Math.random() * data.length);
    this.setState((state) => ({ randomQoute: state.qoute[randomIndex] }));
  }
  render() {
    return (
      <div>
        <h1>Quotes</h1>
        <h2>{this.state.randomQoute.text}</h2>
//this is the button element 
        <button onClick={this.newQoute}>New Qoute</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

1 Like

check you math function , try to console log it first

I think the math function works fine
I did console log it and the console was displaying random quotes

Did you check the console?
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
Not sure what “data” is in newQoute function.

Ohh yes data was a local variable and I have changed it qoute which is defined in the state and still button not working

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