nytimes / react-tracking

🎯 Declarative tracking for React apps.
https://open.nytimes.com/introducing-react-tracking-declarative-tracking-for-react-apps-2c76706bb79a
Other
1.88k stars 123 forks source link

Overriding an (event) context array #164

Closed huguesbr closed 3 years ago

huguesbr commented 3 years ago

When having an array in a context:

@track({values: [1, 2, 3]})
class MyComp extends Component {}

and tracking from a function (or a decorator comp)

const MyFunc() => {
   const tracking = useTracking()
   return (
     <Button onClick={() => tracking.trackEvent({values: [4]})}/>
   )
}

The event context is [1, 2, 3, 4], is it an expected behaviour?

Here is a demo code -> https://gist.github.com/huguesbr/e8126e5bb21d850ba5d6544080bda2a4

Can I override or configure something in order to REPLACE the context array values with the current event values?

huguesbr commented 3 years ago

If it was not merged by default (or optional, or opt-in by default), I could do a merge by getting current context? But I don't see a nice way to fix this behaviour with the current implementation?

const trackingData = tracking.getTrackingData()
tracking.trackEvent({ ...trackingData, values: [4] });
tizmagik commented 3 years ago

We use deepmerge to merge contextual objects. By default, it looks like deepmerge will concatenate arrays instead of overriding them.

Unfortunately, right now we do not provide a way of overriding the merging functionality, nor do we provide a way to specify any deepmerge options.

A potential workaround would be to use an object instead of an array and then convert the object to an array within your dispatch function.

Another approach might be to propose a PR that accepts a merge function as a react-tracking option that is used instead of the deepmerge one provided by default (similar to how overriding the default dispatch function works today).

huguesbr commented 3 years ago

Thx @tizmagik that's a great suggestion, otherwise will see if I can cook a PR which will accept a merge function option.