0

I have an onClick method to react that changes the state of a property named pointer. The function works on a functional level however the UI does not update with my state unless I double click the button (onClick method). I tried turning the component to a class component to utilize the render method but still no results.

let questions = [
  {
    id: 1,
    title: "This person tends to be quiet"
  },
  {
    id: 2,
    title: "This person is compassionate and has a soft heart."
  },
  {
    id: 3,
    title: "This person is disorganized.."
  }
]
export default class Quiz extends React.Component {
  constructor() {
    super();
    this.state = {
      pointer: 0,
      currentAnswer: ""
    };
  }
  render() {
    return (
<div>
<h1> {questions[this.state.pointer].title}</h1>
<button onClick={(e) => {
                    e.preventDefault();
                      this.setState({
                        pointer: this.pointer++
                      });
                      console.log(this.pointer);
                      this.forceUpdate();
                    }}>
</div>
)
}
tg marcus
  • 157
  • 2
  • 13
  • You seem to be missing some code here, where is the so called click handler? Where are the components connected? Where do you use `setState` or `useState`? – Icepickle Aug 20 '20 at 23:01
  • Its updated now my fault I forgot to look over the code. – tg marcus Aug 20 '20 at 23:03
  • `this.pointer` or `this.state.pointer`? Why `this.forceUpdate()`, Why (although not required) don't you use a class function to at least separate the code from the rendering a bit? (I'll pick `id: 3` here :D ) – Icepickle Aug 20 '20 at 23:04
  • State must be inmutable and this.pointer++ is a mutable action, instead, you should write this.state.pointer + 1 – maurirlz Aug 20 '20 at 23:10

2 Answers2

0

The issue was I needed to put "this.state.pointer + 1" not " this.pointer++ ".Thanks, icepickle

tg marcus
  • 157
  • 2
  • 13
0

You just write it, but at least I will give you an explanation.

Every action on State must be performed in a inmutable manner, basically that means that when you call a setState function, the operation provided to setState must return a new value instead of altering the state directly.

Please take this into account for later operations as it will introduce horrendous side effects on your application.

you can read about it here.

maurirlz
  • 60
  • 9