How to use useEffect() hook with matomo push() method to push the current value of the variable

I am trying to implement Matomo with my React application. But I am enable to find a solution for a problem that I am facing right now. I have a progressbar where I am trying to track the progress of a user, and I am using the useEffect to update the useState variable and inside that useEffect, I am pushing the latest value to the data-layer, and then to matomo via the tag manager. But the _mtm.push() method is always pushing the old value, even though the value of the variable is updated (I did put a console log just to check) and still it’s pushing the old value.

useEffect(() => {
    console.log("this is the index ", currentStoryIndex); // latest value
    const _mtm = window._mtm = window._mtm || []
    _mtm.push({ 'event': 'story_progress_bar' });
    _mtm.push({ 'story_player_embed_story_progress_bar': generateId + "_mtm_slide-" + currentStoryIndex }); // old value
  }, [currentStoryIndex])

Hi @Ash_morker
I don’t really understand ; it seems to be a React problem… Is the value displayed in the console ever updated?

yes, the console value is always the updated value, but the trigger value is the old one. That is why I am so confused, because I am console logging the value before passing it to the _mtm.push().

Hi @Ash_morker
Did you try to use the MTM preview mode?
This can give you some clues on the data-layer state, triggered events, and so on…

Yes, MTM preview mode is already enabled and I can see what value is being pushed to the data layer. So I have put a console log before pushing the value, and after clicking on button, I am comparing the values in the console log and the MTM preview mode variable. And they are different, as in , the console value is the correct one but the data layer value is the previous one.

Hi @Ash_morker
Looking back to your code, I think you update the datalayer AFTER you push the event… then the event uses the value that was stored before… :wink:

HI @Philippe,
Can you please tell me how can I fix this issue, how can I push the event with correct data value? Because I think you are right, the very first call is always pushing the default value that I have configured in variable in matomo tag manager.
Thank you for helping out till now. Thanks a lot.

thanks for the help @heurteph-ei I was confused at first but now I see how stupid the mistake is.

useEffect(() => {
    console.log("this is the index ", currentStoryIndex); // latest value
    const _mtm = window._mtm = window._mtm || []
  _mtm.push({ 'story_player_embed_story_progress_bar': generateId + "_mtm_slide-" + currentStoryIndex }); // old value
    _mtm.push({ 'event': 'story_progress_bar' });
  }, [currentStoryIndex])

this works perfectly.
Thank You

1 Like