Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make my OnClick ReactJS function remember the value I am passing

So, I am trying to make a memory game and I want my function "CompareValue" to remember the last variable I passed
I declared in the script at the beginning MemOne and MemTwo so they are global variables.
Here is my HTML code :

function Start(){
var Cartes = [];
const listes_value = [1,2,3,4,5,6,7,8];
const randomvalue = [...listes_value, ...listes_value].sort(() => Math.random() - 0.5);

Cartes.push(
    <center key={`row`}> 
        <div style={{ display: "flex", justifyContent: "center", margin: "20px 0" }}>
            <div style={{ marginRight: "5px" }}>
                <img src={img} onClick={() => CompareValue(randomvalue[1])} />
            </div>
            <div style={{ marginRight: "5px" }}>
                <img src={img}  onClick={() => CompareValue(randomvalue[2])} />
            </div>
            <div style={{ marginRight: "5px" }}>
                <img src={img}  onClick={() => CompareValue(randomvalue[3])} />
            </div>
            <div>
                <img src={img}  onClick={() => CompareValeur(randomvalue[4])} />
            </div>
        </div></center>

Here is my CompareValue function

function CompareValeur(value){
console.log("value :",value)
console.log("MemOne :",MemOne)
console.log("MemTwo :",MemTwo) 
if (pair % 2 === 0) { 
    var MemOne = value
    console.log("MemOne defined")

    pair++; 
} else { 
    var MemTwo = value
    console.log("MemTwo defined")
    pair++;

}
if (MemOne== MemTwo) { 
    console.log("Success !");
}
return MemTwo, MemOne}

Basically what I want my code to do is remember MemOne, and then compare it to MemTwo when another picture is clicked. But it seems that my function forget my variables at the very moment I return them

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    var MemOne = 0; //Global variable
    var MemTwo = 1; //Global variable
    var pair = 0; //Global variable

Here is how I define them at the beginning of my script. Pair is however not lost but I dont’ understand why

>Solution :

You’re redeclaring a variable inside an if scope.

var MemOne = value => MemOne = value

Reassign, not redeclare

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading