1

I have a handleClick method that calls this.pathAnimation(node);

    animateNext(node) {
        console.log(this.state);
        if (this.state.animatedKeyCounter > this.state.animatedNodesKeys.length) {
            console.log(this.state.animatedNodesKeys)
            this.setState({ animatedKeyCounter: 0});
            this.spawnNode(node);
            return;
        }
        console.log("test: " + this.state.animatedNodesKeys[0]);
        let currNode = this[`nodeRef${this.state.animatedNodesKeys[this.state.animatedKeyCounter]}`].current;
        this.setState(prevState => { return { animatedKeyCounter: prevState.animatedKeyCounter + 1 } });
        (node.value >= currNode.state.value) ? currNode.animateGreen() : currNode.animateRed();
    }

    pathAnimation(node) {
        let nodeBinaryString = Number(node.key).toString(2);
        const keysArray = [];
        for (let index = 1; index < nodeBinaryString.length; index++) {
            let currentBinaryString = nodeBinaryString.slice(0, index);
            let currentKey = parseInt(currentBinaryString, 2);
            keysArray.push(currentKey);
        }

        this.setState({ animatedNodesKeys: keysArray });
        this.animateNext(node);
    }

First, pathAnimation is called from the handleClick method which populates the array, animatedNodesKeys, and stores it in this.state

After that, it calls animateNext(node) which accesses this.state

I would expect to see an array filled with some values, but when I check it in the console it's an empty array. It is also important to note that I know for a fact that the array animatedNodesKeys gets filled because if I access it render() it gives me an array with some values.

My only guess is that for some reason when animateNext(node) is called, the array has still not been set in state or maybe the values that should be there have not been calculated yet. However, animateNext(node) is called after all the code regarding the array, so how could this happen?

Moaaz Assali
  • 147
  • 1
  • 8
  • 1
    "My only guess is that for some reason when animateNext(node) is called, the array has still not been set in state" yes, this is correct because `setState()` is asyncronous. See the documentation for `setState()` for ways to guarantee `animateNext()` is called after state is actually set. – Code-Apprentice Dec 20 '20 at 18:32
  • 1
    It's most likely an asynchronous 'issue'. Set state allows to do 'something else' as part of the call and the second argument is called after the state has been set. E.g. this.setState({ animatedNodesKeys: keysArray }, console.log(this.state));. You might have to check the syntax of that though, but it should show the state immediately after being set. – Chris Adams Dec 20 '20 at 18:37

0 Answers0