Skip to content
Advertisement

React Hooks: useState updater function: Why does this hook remove the object upon drag?

I have a marker on a map which takes this function upon dragging:

  function handleOnDragEndUpdateMarker(e) {
    var markerIndex = e.target.options.marker_index;
    var markerLatLng = e.target.getLatLng(); //get marker LatLng
    markerLatLng.id = markerIndex;
    updateUserMarker(markerLatLng, markerIndex);
  }

That function fires another function updateUserMarker, which is coming from a component via context:

It consumes the index, a new object which contains updated lat and long from the event, & appends an id which will also be from the event.

In the context component, I have this function:

 updateUserMarker: (marker, markerIndex) => {
      console.log('marker, markerIndex ', marker, markerIndex);

      let updatedMarker = user.markers.map(element =>
        element.id == markerIndex ? { ...element, ...marker } : element
      )[0];

      console.log(
        'user.markers[markerIndex] updatedMarker ',
        user.markers[markerIndex],
        updatedMarker
      );
      setUser({
        ...user,
        markers: [
          {
            ...user.markers[markerIndex],
            ...(user.markers[markerIndex] = updatedMarker)
          }
        ]
      });
    },

It works fine with the first objects—lat and lang, but upon adding the second object after the dragging commences it disappears!

Probably should have tried to come here hours ago, but wanted to give it my best effort!

Thank you in advance!

Advertisement

Answer

I am not sure why you used [0] for updatedMarker. I assume that you want to update the marker whose id is matched with markerIndex.

updateUserMarker: (marker, markerIndex) => {
  let updatedMarkers = user.markers.map(element =>
    element.id == markerIndex ? { ...element, ...marker } : element
  );
  
  setUser({
    ...user,
    markers: [...updatedMarkers]
  });
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement