Ana
Ana

Reputation: 120

React need this in the useEffect but not as a dependency

i need an opinion on how to solve this. i have the following code:

    const {map, items} = props;
    const [infoWindow, setInfoWindow] = useState(null);
    const [renderedItems, setRenderedItems] = useState([]);

    useEffect(() => {
        const open = (marker, content) => {
            infoWindow.close();
            infoWindow.setContent(content)
            infoWindow.open(map, marker);
        } 

        if(map && items){
            renderedItems.forEach(e => e.setMap(null));
            const newRender = [];
            items.forEach(e => {
                const newMarker = new window.google.maps.Marker({
                    position: e.location
                });
                    
                if(e.content){
                    newMarker.addListener("click", () => open(newMarker, e.content));
                }
                
                newRender.push(newMarker);
                newMarker.setMap(map);
            });
    
            setRenderedItems(newRender);
        }
    }, [map, items, infoWindow]);
 

i keep having the react warning that renderedItems should be in the dependency. if i do that, this renders without end, but i cant take this out of here. cause i need to save the reference of this new created markers

Upvotes: 0

Views: 108

Answers (1)

marcos
marcos

Reputation: 4510

it's normal that the warning pops up, it will check for every variable/function inside your useEffect, if u r certain that u don't need to trigger it when renderedItems change u can disable it:

    useEffect(() => {
        const open = (marker, content) => {
            infoWindow.close();
            infoWindow.setContent(content)
            infoWindow.open(map, marker);
        } 

        if(map && items){
            renderedItems.forEach(e => e.setMap(null));
            const newRender = [];
            items.forEach(e => {
                const newMarker = new window.google.maps.Marker({
                    position: e.location
                });
                    
                if(e.content){
                    newMarker.addListener("click", () => open(newMarker, e.content));
                }
                
                newRender.push(newMarker);
                newMarker.setMap(map);
            });
    
            setRenderedItems(newRender);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [map, items, infoWindow]);

Upvotes: 2

Related Questions