Code under View Render being triggered twice

My code block for a particular view is triggered twice for no apparent reason… There are no duplications and the function is not called twice. Has anyone else faced this issue and how can you overcome it?

Hi Arjun. I’ve seen this happen in a Search view. What type of view is it? Can you share all of the relevant code?

Hey @KnackPros. Yes this is a search view as well. I had a feeling that something in my code might trigger this so I commented everything out and just have the following code block but still it triggers twice if using ‘knack-records-render’ and thrice if using ‘knack-view-render’. There are no additional views in the scene either.

$(document).on('knack-view-render.view_808', async function (event, view, records) {
    event.preventDefault();
    event.stopImmediatePropagation();
    console.log(event);
});

Attaching console output screenshot for reference.

Try this workaround (see below)

$(document).on('knack-view-render.view_808', async function(event, view, records) {
  if (!window.rendering) {
    window.rendering = true

    // Add your code here
    // ... 

    setTimeout(function() {
      window.rendering = false
    }, 500)
  }
})

It sets a flag when the render starts and removes it after a brief pause, just long enough to block Knack’s extra trigger(s). You can set the time as low as 50 milliseconds if you’d like and it still works. In a real app you probably want to use a more specific variable than rendering such as view_808_rendering.

This is just a workaround, of course. I would be interested to know why Knack decided that Search Views should behave this way; it seems they did it this way on purpose. If you get any information from the internal team please update this thread.

:slightly_smiling_face:

This is super weird. The “event.stopImmediatePropagation()” seems to prevent the multiple loads now. Thanks for the input though. I think that will be a much more concrete implementation as my method seems to stop working all of a sudden.

My theory is that having the “Show results to start” enabled in the builder is causing the view or records to be rendered multiple times and thus triggering the code that many times. I have raised a bug report but am yet to hear from the Knack team. Will update on responses.

Tested your workaround and it works great. I’m marking it as the solution for now till we have a more concrete solution from Knack.

1 Like