Quote Generator - React, JS

Hey there!
So I have the basic building blocks for the app, but I am trying to figure out how to generate a random number so that the previous number is different from the next number. Here is the code I have:

newIndex() {
    let lastIndex = 0;
    let index = Math.floor(Math.random() * quotes.length);
    if(lastIndex !== index) {
       lastIndex = index;
    } else {
      lastIndex = Math.floor(Math.random() * quotes.length);
    }
    return lastIndex;
  }

I want to use this function as the index for returning quotes from an array. Here is the code:

handleClick() {
      this.setState({
        quote: quotes[this.newIndex].quote,
        author: quotes[this.newIndex].author
      });
    }

What I have doesn’t seem to be working. Any react people know what I’m doing wrong?

Here is the codepen link: https://codepen.io/bstefansen/pen/vYEWKBo

Thanks y’all!

So, the first step I’ve come up with is to combine the functions. This seems to allow the program to work, but it still doesn’t do what I want :frowning:

handleClick() {
    let lastIndex = 0;
    let index = Math.floor(Math.random() * quotes.length);
    if(lastIndex !== index) {
       lastIndex = index;
    } else {
      lastIndex = Math.floor(Math.random() * quotes.length);
    }
      this.setState({
        quote: quotes[lastIndex].quote,
        author: quotes[lastIndex].author
      });
    }

I have used the state to store the random number.

  constructor(props) {
    super(props);
    this.state = {
        quotes: [],
        rndNum: Math.floor(Math.random() * 500),
    }
    this.handleClick = this.handleClick.bind(this);
}
componentWillMount = () => {
    fetch('https://jsonplaceholder.typicode.com/comments')
    .then(res => res.json())
    .then(data => this.setState({quotes: data}))
  }
  handleClick() {
 this.setState({rndNum: Math.floor(Math.random() * 500)})           
};

The chance to get the same quote twice is 1 to 500 … but you could extend this code if you really want to…

Something like:

...
  handleClick() {
let i;
for (i = 0; i < 99; i++) {
let test = Math.floor(Math.random() * 500)
if (test !== this.state.rndnum) {
this.setState({rndNum: test})
break;
};
};

Best regards

Nice! I will try these out.

Thank you sir!

Dear coder,
does it work?

Yep, sure does. Thanks again!

1 Like