Search code examples
reactjsfindreact-konvakonva

Cannot read property 'apply' of undefined Konva.js


I'm trying to find object by using method find. It is only a part of code, just to demonstrate issue. In general I need to find object from array of Shapes from Konva framework. I got it by using refs after rendering functional component.

import React, { useState, useEffect, useRef } from "react";
import Konva from "konva";
import { Stage, Layer, Text, Circle } from "react-konva";

import { ArrowComp } from "./Arrow";
import { useInterval } from "../hooks/useInterval";

const Graph = props => {
    const [data, setData] = useState({
        circles: ConvertMatrix(matrix).circles,
    });
        const circles = ref.current.find(".circle");
    const stageRef = useRef();
    useEffect(() => {
        const circles = stageRef.current.find(".circle");
        const finded = circles.find((circle) => circle.attrs.radius < 50)
    }, []);

    return (
        <Stage
            width={window.innerWidth}
            height={window.innerHeight}
            className="container"
            ref={stageRef}
        >
            <Layer>
                   <Circle
                      shadowBlur={10}
                      x={150}
                      y={200}

                      radius={circle.r || 40}
                      fill="yellow"
                      name={"circle"}
                      id={1}
                    /> 
                     <Circle
                      shadowBlur={10}
                      x={150}
                      y={150}
                      radius={40}
                      fill="yellow"
                      name={"circle"}
                      id={2}
                    />        
            </Layer>
        </Stage>
    );
};


ReactDOM.render(<Graph />, document.querySelector("#app"))

and I get error in lib. Is it konva framework library? How can I find element from array by the other way?

     16 |     var len = this.length, i;
  17 |     var args = [].slice.call(arguments);
  18 |     for (i = 0; i < len; i++) {
> 19 |         this[i][methodName].apply(this[i], args);
     | ^  20 |     }
  21 |     return this;
  22 | };

TypeError: Cannot read property 'apply' of undefined Collection. [as find]

Thats my first question on StackOwerflow, sorry for the question not quite in the format. I made an example here

UPD: solved problem by using findIndex and got value by circles[index]. But 1 questionl left: is it bug of the library(framework)?


Solution

  • Your circles variable is not an array. stage.find(selectors) returns a Konva.Collection. It works a bit differently from the Array. If you want to have an array just use:

    circles.toArray().find((circle) => circle.radius() < 50);