-1

So I have an array of items that are randomly displayed:

const questions = this.state.questions
            .sort(() => Math.random() - Math.random())
            .find(() => true);

And I have a button. If I click on this button, I want to put the content of the displayed item:

                      {questions && (
                            <div>
                                <div className="questions-card">
                                    {questions.question}
                                </div>
                                <div>
                                    <Button
                                        onClick={() =>
                                            this.setState({
                                                question: questions.question,
                                            })
                                        }
                                    >
                                        Answer
                                    </Button>
                                </div>
                            </div>
                        )}

I don't know why, but every time I click on this button, it skips to the next item. I don't want this. All I want is to put questions.question in the state. What's going on?

David
  • 321
  • 10
  • 23
  • Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Jul 02 '20 at 07:40
  • 1
    What do you mean by it skips to the next item ? Anyway, the problem is probably linked to the fact that you have a non deterministic render, you should keep the random order of questions in state. You're also mutating the state in each render. – Axnyff Jul 02 '20 at 07:40
  • if `questions` is an array, what is `questions.question` ? – Gabriele Petrioli Jul 02 '20 at 07:40
  • There are many objects in this array, and `questions.question` is one of the objects' field. I randomly render an array of questions. It displays 1 question at a time, which is good. How to keep the random order of questions in the state? Do that in the axios get request? – David Jul 02 '20 at 07:45
  • can you upload your code so it's testable – EugenSunic Jul 02 '20 at 07:47

2 Answers2

-1

So this is happening because page rerenders each time you click on a button.

See more here:
ReactJS - Does render get called any time "setState" is called?

Yaroslav
  • 110
  • 4
-1

The problem was this line:

.sort(() => Math.random() - Math.random())

So had to sort it randomly on the back-end side, MongoDB in my case:

let questions = await Question.aggregate([
                { $sample: { size: 1000 } },
            ]);
David
  • 321
  • 10
  • 23