Value updates only once

    const colors = ["green", "blue", "red", "yellow", "purple", "pink"]
    let timesClicked = 0

const handleMarkerClick = (lat, lng) => {
        if (timesClicked === 5) {
            timesClicked = 0
        } else { timesClicked++ }
        setMarkers(prev => prev.map(item => {

            if (item.lng === lng && item.lat === lat) {
                return { ...item, color: colors[timesClicked] }
            } else { return item }
        }))
        console.log(timesClicked)
    }

For some reason, timesClicked increments only once and remains the same after I click on the marker several more times. Can anyone help me with this?
(I am using React and I’ve also tried with useState)

Please share the code for the entire React component.

import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"
import React, { useContext, useState } from "react"
import { DataContext } from "./Data"




export const MyMapComponent = withScriptjs(withGoogleMap((props) => {

    let { markers, setMarkers, timesClicked, setTimesClicked, colors } = useContext(DataContext)

    const handleClick = (e) => {
        const lat = parseFloat(e.latLng.lat());
        const lng = parseFloat(e.latLng.lng());
        setMarkers(prev => [...prev, { lat, lng }])
        localStorage.setItem("markers", [...markers])
    }


    const handleMarkerClick = (lat, lng) => {
        setTimesClicked(timesClicked++)
        setMarkers(prev => prev.map(item => {
            if (item.lng === lng && item.lat === lat) {
                return { ...item, color: colors[timesClicked] }
            }
            return item
        }))
        console.log(timesClicked)
    }

    const handleRightClickMarker = (lat, lng) => {
        setMarkers(prev => prev.filter(item => item.lng !== lng && item.lat !== lat))
    }

    return <GoogleMap
        defaultZoom={8}
        defaultCenter={{ lat: -34.397, lng: 150.644 }}
        onClick={handleClick}
    >
        {markers.map((item, key) => {
            let color = item.color ? `http://maps.google.com/mapfiles/ms/icons/${item.color}.png` : "http://maps.google.com/mapfiles/ms/icons/red.png"
            return <Marker key={key} position={{ lat: item.lat, lng: item.lng }} icon={color} onRightClick={() => handleRightClickMarker(item.lat, item.lng)} onClick={() => {
                handleMarkerClick(item.lat, item.lng)
            }} />
        })}
    </GoogleMap>
}
))


Try changing this line setTimesClicked(timesClicked++) to use the prefix operator setTimesClicked(++timesClicked). Increment (++) - JavaScript | MDN

1 Like

I have no idea how, but it works!
Thanks a lot!