infernojs / inferno

:fire: An extremely fast, React-like JavaScript library for building modern user interfaces

Home Page:https://infernojs.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Something is wrong with setState

ufukbakan opened this issue · comments

Observed Behaviour

Inferno setState is not managed from single point thus providing a state setter function callback is not working as expected.
Code example below represenets a simple timer based counter:

import { Component, type InfernoNode } from 'inferno'
import './App.css'
import Logo from './logo'

interface AppState {
  count: number
}

export default class App extends Component<Record<any, any>, AppState> {
  state: AppState = {
    count: 0
  }

  incrementCount = (): void => {
    this.setState(p => ({ ...p, count: p.count + 1 }))
  }

  componentDidMount(): void {
    setTimeout(this.incrementCount, 1000)
  }

  render(): InfernoNode {
    return (
      <div className="App">
        <header className="App-header">
          <Logo width={80} height={80} />
          <h2>Count = {this.state.count}</h2>
        </header>
      </div>
    )
  }
}

It sets 'count' state to always 1

Expected Current Behaviour
It should set count state to count+1 every second. It should go as 1,2,3....

Inferno Metadata
"inferno": "^8.2.3",
"inferno-scripts": "8.0.17",
"typescript": "^5.3.3",
"web-vitals": "^3.5.0"

Microsoft Edge
Version 120.0.2210.91 (64 bit)

I dont see any bug here, maybe I'm missing something? If you want to call the state every second then you should use setInterval not setTimeout.

componentDidMount function callback will be called once when the components mounts thus only one iteration is expected.

Please re-open if there is something more to this

yeah my ai code assistant suck, sorry. i will think twice before using "fix with copilot" button again