Home > Enterprise >  Recurring function with useState - React
Recurring function with useState - React

Time:12-03

I have read up on hashing iteration and although this is not a question about security I can´t seem to find information on how to actually do this correct.

I thought that when in React, this should be done with useState, but im clearly missing something here.

Full code:

import { sha256 } from "js-sha256";
import { useState } from "react";

function App() {
  const [currentHash, setCurrentHash] = useState("summer1");

  function iterate(iterations) {
    for (let x = 0; x < iterations; x  ) {
      setCurrentHash(sha256(currentHash)); //Does 1 hash only
      console.log("Hashed", x, "times"); //Logs 4 times
    }
  }

  return (
    <div className="App">
     
        <button onClick={() => iterate(4)}> Klick</button>
        currentHash: {currentHash}
        {/* Correct hashes */}
        <p>0: summer1</p>
        <p>1: {sha256("summer1")}</p>
        <p>2: {sha256(sha256("summer1"))}</p>
        <p>3: {sha256(sha256(sha256("summer1")))}</p>
        <p>4: {sha256(sha256(sha256(sha256("summer1"))))}</p>
 
    </div>
  );
}

export default App;

CodePudding user response:

sha256(currentHash) is going to give you the same result no matter how many times you run it.

currentHash won't be updated until the component is re-rendered and a new value is pulled out of the state and assigned to the new instance of currentHash at the top of the function.

You need to:

  1. store the result in a variable — not the state
  2. use the value of that variable as the input to the function
  3. store the final result in the state at the end

CodePudding user response:

Working code:

import { sha256 } from "js-sha256";
import { useState } from "react";

function App() {
  const [currentHash, setCurrentHash] = useState("");

  function iterate(input, iterations) {
    for (let x = 0; x < iterations; x  ) {
      input = sha256(input);
      console.log("Hashed", x, "times");
    }
    setCurrentHash(input)
  }

  return (
    <div className="App">
      
        <button onClick={() => iterate("summer1", 2)}> Klick</button>
        currentHash: {currentHash}

    </div>
  );
}

export default App;

  • Related