Render item from an array after a fixed interval in React

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I want to array items on after another. But it is only displaying the last element of the array.

Expeb.com/tag/c">cted output is displaying "a" after 2 seb.com/tag/c">conds "b" and so on.

import Reab.com/tag/c">ct, { Component } from "reab.com/tag/c">ct"

export default b.com/tag/c">class Main extends Component {
  b.com/tag/c">construb.com/tag/c">ctor(props) {
    super(props)
    this.state = {
      role: ["a","b","b.com/tag/c">c"],
      display: "",
    }
  }
  b.com/tag/c">componentDidMount() {
      for (let i of this.state.role) {
        setTimeout(() => {
          this.setState(() => { display: i})
        }, 2000)
      }
    })
  }

  render() {
    return (
      <>
          <h3>{this.state.display}h3>
      
    )
  }
}
profilepic.png
manpreet 2 years ago

The problem is that you are using a loop to create a timeout on componentDidMount. In such a case what would happen is that the loop will complete immedialtely creating 3 timers which resolve at nearly the same 2sec interval from the start and setState then batches all the three state update calls resulting in only the last one to be displayed.

In order to solve this you can make use of setInterval like below

class Main extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      role: ["a","b","c"],
      display: "",
    }
  }
  componentDidMount() {
    var index = 0;
    this.timer = setInterval(() => {
      this.setState({ display: this.state.role[index]});
      index  = (index + 1)%(this.state.role.length);
    }, 2000)
  }

  componentWillUnmounnt() {
    clearInterval(this.timer);
  }
  render() {
    return (
      <React.Fragment>
          <h3>{this.state.display}h3>
      React.Fragment>
    )
  }
}

ReactDOM.render(<Main />, document.getElementById('root'));

src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"> src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"> id="root"/>

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.