Dmitry Ermichev
Dmitry Ermichev

Reputation: 423

React redux prevent updating component from old state

I have map component, which map center location is connected to redux state.

<YandexMapView
                ref={this._mapRef}
                location={this.props.location}
                onInteraction={(event) => this.onMapPositionChanged(event)}
                geocodingEnabled={true}
                onGeocoding={(event) => this.onGeocoding(event)}
            />

My saving function is

onMapPositionChanged(event: OnInteractionResult) {
    const {latitude, longitude} = event;
    this.props.dispatch(updateLocation({
        latitude, longitude,
    }));
}

When I move map, and after that I move it again in a short time, before my old state will update to component I have infinite jitter effect.

The abnormal sequence is:

  1. Component send event to update state with data {latitude: 1, longitude: 1}.

  2. State is updated to {latitude: 1, longitude: 1}.

  3. At that time component send another event to update state = {latitude: 2, longitude: 2} because I moved the map.

  4. Component receive old state in props = {latitude: 1, longitude: 1}

  5. Component updates its map location to old {latitude: 1, longitude: 1} and send again {latitude: 1, longitude: 1}

and all these actions become infinite...

I tried to add delay or throttle to my redux sagas, but it doesn't help.

Upvotes: 0

Views: 321

Answers (1)

NiFi
NiFi

Reputation: 2458

You need to separate events from map movement initiated by the user from events generated by moving the map programmatically. You likely want to call onMapPositionChanged only for events from the user moving the map.

You haven't specified which library you are using, but for React Native e.g. doomsower/react-native-yandexmapkit's onInteraction callback has a type attribute that can be used for this purpose. Whatever library you are using probably supports something similar.

Upvotes: 1

Related Questions