DoghouseReilly
DoghouseReilly

Reputation: 3

Falling into an infinite for loop in react when I try to loop over a string

What I'm trying to do: The app I'm working on in React takes two blocks of userinputted text, slices them up into substrings of 30 characters each -- and eventually will randomly recombine these strings. It's a riff on the literary cut-up technique.

Here's what I'm doing:

import React, { useState } from "react";
// import Collage from "./components/collageText/collage";

import "./App.css";

import SrcTxt from "./components/srcTxt/srcTxt";

const App = () => {
  const [txt1, setTxt1] = useState("");
  const [txt2, setTxt2] = useState("");

  const SubmitHandler = (e) => {
    e.preventDefault();

    setTxt1(e.target.userTxt1.value);
    setTxt2(e.target.userTxt2.value);
    
    let cutTxt1 = []
    for (let x = 0; x < txt1.length - 31; x + 31){
      cutTxt1.push(txt1.slice(x, x+31))
    }
    console.log(cutTxt1)
  };

  return (
    <div>
      <h1>howdy</h1>
      <SrcTxt submitted={SubmitHandler} />
    </div>
  );
};

export default App;

The issue is in how I'm looping through the inputted string. When I run the code, at first nothing logs to the console; if I click submit again, it runs the program infinitely.

I'm pretty sure I'm missing something painfully obvious here.

Upvotes: 0

Views: 110

Answers (2)

reobin
reobin

Reputation: 59

The reason why nothing happens on the first time is that setTxt1(e.target.userTxt1.value); will only update the value of txt1 on the next render. That means that the variable is not immediately defined and usable.

I suggest defining a variable local to your function, do what you want with it, and then setting your state.

  const SubmitHandler = (e) => {
    e.preventDefault();

    const txt1 = e.target.userTxt1.value;
    const txt2 = e.target.userTxt2.value;

    let cutTxt1 = []
    for (let x = 0; x < txt1.length - 31; x += 31){
      cutTxt1.push(txt1.slice(x, x+31))
    }

    console.log(cutTxt1);

    setTxt1(txt1);
    setTxt2(txt2);
  };

The infinite loop comes from not updating the x value, as others said. Add the += when incrementing x to update its value.

Upvotes: 1

Igor Bykov
Igor Bykov

Reputation: 2822

Looks like you never modify x.

You likely meant x += 31 instead of x + 31.

Upvotes: 0

Related Questions