I can't access html element inside useEffect

Viewed 66

I want to generate itinerary control (table element) generated in <RoutingMachine />. But I cannot access html element in useEffect because it still not exist.

const Routing = ({ pointA, pointB }) => {

    const dispatch = useDispatch()

    const createLayer = () => {
        const instance = L.Routing.control({
            waypoints: [
                L.latLng(pointA.position.lat, pointA.position.lng),
                L.latLng(pointB.position.lat, pointB.position.lng)
            ],
            lineOptions: {
                styles: [{ color: "red", weight: 4 }]
            },
        });

        return instance;
    };

    const RoutingMachine = createControlComponent(createLayer);

    useEffect(() => {
        let routeInfo = document.querySelectorAll('tr')
        console.log(routeInfo) // array with 0 elements
    }, []);

    return <RoutingMachine />

};
2 Answers

Can you try this (with useRef()):

const Routing = ({ pointA, pointB }) => {

    const dispatch = useDispatch()
    const mounted = useRef(true)

    const createLayer = () => {
        const instance = L.Routing.control({
            waypoints: [
                L.latLng(pointA.position.lat, pointA.position.lng),
                L.latLng(pointB.position.lat, pointB.position.lng)
            ],
            lineOptions: {
                styles: [{ color: "red", weight: 4 }]
            },
        });

        return instance;
    };

    const RoutingMachine = createControlComponent(createLayer);

    useEffect(() => {
        if (mounted.current) {
          let routeInfo = document.querySelectorAll('tr')
          console.log(routeInfo) // array with 0 elements
        }

        return () => {
          mounted.current = false;
        }
    }, [mounted]);

    return <RoutingMachine />

};

You can use references supported by leaflet, checkout this Reference

Related