0

i'm trying to randomize the results I receive from the API everytime I refresh the page. I´m a little bit stuck in which way to set up the onload.

This is my code

  handleRandom = (e) => {
    this.getMarvelResponse(null, null, e);
  };
  componentDidMount() {
    const random = Math.floor(Math.random() * 1473);
    this.getMarvelResponse(null, null, this.state.offset);
    onload = () => {this.handleRandom(random)}
  }

  getMarvelResponse = (id, name, offset) => {
    getCharacters({
      id: id,
      name: name,
      offset: offset,
    }).then(({ characters }) => {
      this.setState(
        {
          characters: characters.filter(
            (chr) => !chr.thumbnail.path.match(imageFound)
          ),      

          selectedCard: null,
          offset: offset,
          name: name,
        },
        () => {
          console.log(this.state.characters);
        }
      );
    });

1 Answers1

0

You are going to have to create a function to shuffle them. https://stackoverflow.com/a/12646864/11765805 I got this from this comment

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

You will want to call it here

  getMarvelResponse = (id, name, offset) => {
    getCharacters({
      id: id,
      name: name,
      offset: offset,
    }).then(({ characters }) => {
/////////Call Here
      this.setState(
        {
          characters: characters.filter(
            (chr) => !chr.thumbnail.path.match(imageFound)
          ),      

          selectedCard: null,
          offset: offset,
          name: name,
        },
        () => {
          console.log(this.state.characters);
        }
      );
    });
saladWithRanch
  • 158
  • 1
  • 2
  • 9