April Henig
April Henig

Reputation: 47

Trying to add one letter at a time to state in React

I'm trying my best to add a single letter every 2 seconds to state in React. For some reason I get the whole word ("Welcome"), instead of one letter at a time. Here's my code:

import React from "react";

    class ShowState extends React.Component {
      constructor() {
        super();
        this.state = {
          word: ""
        };
      }
    
      handleButton = () => {
        let welcome = "Welcome";
        for (let letter of welcome) {
          setInterval(() => {
            this.setState((prevState) => ({
              word: prevState.word + letter
            }));
          }, 2000);
        }
      };
    
      render() {
        return (
          <div>
            <button onClick={this.handleButton}>Click ME!</button>
            <div className="input"></div>
            <h2>{this.state.word}</h2>
          </div>
        );
      }
    }
    
    export default ShowState;

Thanks for your time and help!

Upvotes: 0

Views: 957

Answers (2)

Viet Dinh
Viet Dinh

Reputation: 1961

You have set setState for all laters for 2000. Mean after 2s it will call mutil setState, it cause print all word.

Here my idea:

handleButton = () => {
    let welcome = "Welcome";
    let index = 0;
    for (let letter of welcome) {
        index++;

        setTimeout(() => {
            this.setState((prevState) => ({
                word: prevState.word + letter
            }));
        }, index*2000);
    }
};

Updated idea with repeat:

   handlePrintWord = (word, time) => {
        let index = 0;

        for (let letter of word) {
            index++;

            setTimeout(() => {
                this.setState((prevState) => ({
                    word: prevState.word + letter
                }));
            }, index*time);
        }
    }

    handleButton = () => {
        const welcome = "Welcome";
        const time = 2000;

        //first time
        this.handlePrintWord(welcome, time);

        //if you want repeat
        setInterval(() => {
            this.handlePrintWord(welcome, time);
        }, (welcome.length) * time);

    };

Upvotes: 3

Senior0023
Senior0023

Reputation: 162

You need to use setTimeout() rather than setInterval(). setTimeout() triggers the expression only once, but setInterval() keeps triggering expression regularly after the given interval of time.

Upvotes: 0

Related Questions