pomber / didact

A DIY guide to build your own React

Home Page:https://pomb.us/build-your-own-react/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useState not work in multiple case (with setTimeout)

shadowvzs opened this issue · comments

@pomber

1. Issue with setTimeout

const element = <Test />
const container = document.getElementById("root")
render(element, container)
const Test = (): JSX.Element => {
    document.title = `Home Page`;

    const [s, setS] = useState(10);

    setTimeout(() => {
        setS(Math.random());   // result is error in this moment
    }, 5000);

    return (
        <div>
            <h1 onClick={() => setS(c => c + 1)}>
                Count: {s}
            </h1>
        </div>
    );
}
export function useState(initial) {
    ...........
    actions.forEach(action => hook.state = action(hook.state)); // here the action is a number and not the function which should set the value
    // TypeError: action is not a function 
    ........

2. Issue with setTimeout

same code just with directly called element

const element = Test();
const container = document.getElementById("root")
render(element, container)
export function useState(initial) {
    // wipFiber is     ##@@null
    const oldHook = wipFiber.alternate && wipFiber.alternate.hooks && wipFiber.alternate.hooks[hookIndex];

use state not work if i call it from set timeout / interval

Not sure if you figured it out, in didact setState only accepts a function as the parameter. So, you shouldn't use setState(newState) but setState(oldState => newState).

Not sure if you figured it out, in didact setState only accepts a function as the parameter. So, you shouldn't use setState(newState) but setState(oldState => newState).