TransWikia.com

In React, calling state twice, but second one always one step behind?

Stack Overflow Asked by Lawrence Yoon on January 17, 2021

In React, onButtonClick method updates state on currentIndex properly, but not on the currentText. If you check out the two console logs, you’ll see that currentText lags behind one. How can I fix it in the same setState call? Does it have to do with React being asynchronous?

// dependencies
import React from 'react';
// local files
import './App.css';

const sections = [
  {
    title: 'Section 1',
    content: 'Lorem ipsum dolor sit amet consectetur adipisicing elit.',
  },
  {
    title: 'Section 2',
    content: 'Cupiditate tenetur aliquam necessitatibus id distinctio quas nihil ipsam nisi modi!',
  },
  {
    title: 'Section 3',
    content: 'Animi amet cumque sint cupiditate officia ab voluptatibus libero optio et?',
  },
]

class App extends React.Component {
  // state
  state = {
    currentIndex: 0,
    currentText: ''
  };

  // event handlers
  onButtonClick(index) {
    this.setState({
      currentIndex: index,
      currentText: this.state.currentIndex
    }, function() {
      console.log(this.state.currentIndex);
      console.log(this.state.currentText);
    });
  }

  // helpers
  renderButtons() {
    return sections.map((item, index) => (
      <li key={item.title}>
        <button onClick={() => this.onButtonClick(index)}>{item.title}</button>
      </li>
    ));
  }

  renderContent() {
    return this.state.currentText;
  }

  render() {
    return (
      <div className="App">
        <ul>
          {this.renderButtons()}
        </ul>
        <p>{this.renderContent()}</p>
      </div>
    );
  };
}
export default App;

2 Answers

Do this instead:

  onButtonClick(index) {
    this.setState({
      currentIndex: index,
      currentText: index
    }, function() {
      console.log(this.state.currentIndex);
      console.log(this.state.currentText);
    });
  }

Correct answer by Jkarttunen on January 17, 2021

This might help

onButtonClick(index) {
    this.setState({
      ....
      currentText: sections[index].title, // update text also when selected
    }, function() {
      .....
    });
  }

Answered by Nooruddin Lakhani on January 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP