Recurring function with useState - React - javascript

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;

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:
store the result in a variable — not the state
use the value of that variable as the input to the function
store the final result in the state at the end

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

for loop wont work in a function inside react component

import React from 'react';
const RowArray=()=>{
return(
<div>
<h1>Row Array</h1>
</div>
)
};
const chunk_array = (list, integer)=>{
let temp_arr = list;
console.log('chunks',list,'integer',integer);
const list_of_chunks = [];
const iteration = Math.ceil(+list.length/+integer);
// list.map(x => {console.log(x,"map")})
for (let i;i< iteration ;i++ ){
console.log(i);
let temp_chunk = temp_arr.splice(6, temp_arr.length);
list_of_chunks.push(temp_chunk);
};
return list_of_chunks;
}
const TableArray=({details})=>{
const data = chunk_array(details);
console.log('data', data);
return(
<div className="d-flex flex-row">
<RowArray/>
</div>
)
};
export default TableArray;
the for loop in function chunk array won't work, supported as no i was logged in the console. I understand in jsx for loop may not work, I believe I define the function in pure javascript enviroment, so why do you think it is?
Console.log(i) doesn't log anything, as in the function skipped for loop line
you haven't initialized the value of i in the for loop
for (let i = 0; i < iteration; i++) {
// your code
}
chunk_array function expects two arguments and you're only passing one argument details

React child not updating a variable of parent through function

So I'm learning react at the moment and I've been struggling with this issue..
I'm trying to do tic-tac-toe so I've got this code:
import './App.css';
import { useState } from "react"
const X = 1;
const O = -1;
const EMPTY = 0;
var Square = ({idx, click}) =>
{
let [val, setVal] = useState(EMPTY);
return (
<button onClick={() => {click(setVal, idx);}}>{val}</button>
)
}
var Logger = ({state}) =>
{
return (
<button onClick={() => {console.log(state);}}>log</button>
)
}
var App = () =>
{
let [turn, setTurn] = useState(X);
let state = new Array(9).fill(EMPTY);
let squares = new Array(9);
let click = (setValFunc, idx) =>
{
setTurn(-turn);
setValFunc(turn);
state[idx] = turn;
}
for (let i = 0 ; i < 9 ; i++)
{
squares[i] = (<Square click={click} idx={i}/>);
}
return (
<>
<Logger state={state} />
<div>
{squares}
</div>
</>
)
}
export default App;
so the squares ARE changing as I click them, but when I click the log button to log the state array to the console, the state array remains all zeros.
what am I missing here?
Your state has to be a React state again. Otherwise, the state you defined inside the App as a local variable only lasts until the next rerender.
Maintain tic-tac-toe state inside a useState hook
let [state, setState] = useState(new Array(9).fill(EMPTY));
Update the click handler accordingly.
let click = (setValFunc, idx) => {
setTurn(-turn);
setValFunc(turn);
setState((prevState) =>
prevState.map((item, index) => (index === idx ? turn : item))
);
};
In React, the state concept is important.
In your case, you need to understand what is your state and how you can model it.
If you are doing a Tic-Tac-Toe you will have:
the board game: a 3 by 3 "table" with empty, cross or circle signs
This can be modeled by an array of 9 elements as you did.
But then you need to store this array using useState otherwise between -re-renders your state array will be recreated every time.
I advise you to read https://reactjs.org/docs/lifting-state-up.html and https://beta.reactjs.org/learn.

React event-handler shows the same index value

have a simple React component that displayes a character and should call a handler when clicked, and supply a number. The component is called many times, thus displayed as a list. The funny thing is that when the handler is called, the supplied index is always the same, the last value of i+1. As if the reference of i was used, and not the value.
I know there is a javascript map function, but shouldn't this approach work too?
const charComp = (props) => {
return (
<div onClick={props.clicked}>
<p>{props.theChar}</p>
</div>
);
deleteHandler = (index) => {
alert(index);
}
render() {
var charList = []; // will later be included in the output
var txt = "some text";
for (var i=0; i< txt.length; i++)
{
var comp =
<CharComponent
theChar = {txt[i]}
clicked = {() => this.deleteHandler(i)}/>;
charList.push(comp);
}
Because by the time you click on a letter, i is already 9 and it will remain 9 since the information is not held anywhere.
If you want to keep track of the index you should pass it to the child component CharComponent and then pass it back to the father component when clicked.
const CharComponent = (props) => {
const clickHandler = () => {
props.clicked(props.index);
}
return (
<div onClick={clickHandler}>
<p>{props.theChar}</p>
</div>
);
};
var comp = (
<CharComponent theChar={txt[i]} index={i} clicked={(index) => deleteHandler(index)} />
);
A little codesandbox for ya

Component does not render, but react does not show errors

I am trying to create an application that will sort the array from the smallest to the largest, but at the very beginning I encountered an error. React does not show a single error and the component does not render anyway.
App.js
import { SortingVizualize } from './SortingVizualize/SortingVizualize';
function App() {
return (
<div className="App">
<SortingVizualize />
</div>
)
}
export default App;
SortingVizualize.jsx
import React from 'react';
// import styles from './SortingVizualize.modules.scss';
export class SortingVizualize extends React.Component {
constructor(props) {
super(props);
this.state = {
array: [],
};
}
componentDidMount() {
this.resetArray();
}
resetArray() {
// I use this method to generate new array and reset
const array = [];
for (let i = 0; i < 100; i++) {
array.push(randomInt(5, 750)); // Min and Max value of number in array
}
}
render() {
const { array } = this.state;
return (
<>
{array.map((value, idx) => (
<div className="array-bar" key={idx}>
{value}
</div>
))}
</>
)
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
export default SortingVizualize;
Your state.array and the array in resetArray are two different arrays and you never update the one in the state.
You will need to call setState to update the state
resetArray() {
// I use this method to generate new array and reset
const array = [];
for (let i = 0; i < 100; i++) {
array.push(randomInt(5, 750)); // Min and Max value of number in array
}
this.setState({ array });
}
You're not triggering any update events since you're using array.push to a local variable, which then isn't assigned to the component state. Remember to use this.setState(...) to update the array saved in your state, like so:
resetArray() {
// I use this method to generate new array and reset
const array = [];
for (let i = 0; i < 100; i++) {
array.push(randomInt(5, 750)); // Min and Max value of number in array
}
this.setState({
array,
});
}
In your resetArray method you're not assigning your data to your state. Your state's array field still empty then. You may add this.setState({ array }) in order to trigger the rerender with generated data.

React warning: Functions are not valid as a React child

I have this react component. This is not rendering properly but getting an annoying warning like
Functions are not valid as a React child. This may happen if you return a Component instead of from the render. Or maybe you meant to call this function rather than return it.
Here's my component. What am I doing wrong here?
import React, { Component } from 'react';
class Squares extends Component {
constructor(props){
super(props);
this.createSquare = this.createSquare.bind(this);
}
createSquare() {
let indents = [], rows = this.props.rows, cols = this.props.cols;
let squareSize = 50;
for (let i = 0; i < rows; i++) {
for (let j = 0; i < cols; j++) {
let topPosition = j * squareSize;
let leftPosition = i * squareSize;
let divStyle = {
top: topPosition+'px',
left: leftPosition+'px'
};
indents.push(<div style={divStyle}></div>);
}
}
return indents;
}
render() {
return (
<div>
{this.createSquare()}
</div>
);
}
}
export default Squares;
UPDATE
#Ross Allen - After making that change, the render method seems to be in infinite loop with potential memory crash
You need to call createSquare, right now you're just passing a reference to the function. Add parentheses after it:
render() {
return (
<div>
{this.createSquare()}
</div>
);
}
React uses JSX to render HTML and return function within render() should contain only HTML elements and any expression that needed to be evaluated must be within { } as explanied in https://reactjs.org/docs/introducing-jsx.html. But the best practice would be to do any operation outside return just inside render() where you can store the values and refer them in the return() and restrict usage of { } to just simple expression evaluation. Refer for In depth JSX integration with React https://reactjs.org/docs/jsx-in-depth.html
render() {
var sq = this.createSquare();
return (
<div>
{sq}
</div>
);
Ross Allen's answer is also fine , the point is Inside JSX enclose any operation / evaluation inside { }
You just need to remove () from your function call.
render() {
return (
<div>
{this.createSquare}
</div>
);
}

Categories

Resources