Tuesday, 21 August 2018

SPFx: How OTB News Webpart displays ViewCount


In this blog I'll explain how the out of the box news webpart displays the view count for each promoted site page aka "News Pages". At the first glance when a colleague asked me I answered naively by
"Oh Check ViewCountLifeTime managed property" thinking -silly me- that modern pages webpart will somehow uses the same technique that old publishing pages used to embrace, which has viewCountLifeTime, viewsLastNDays  managed properties which used to give us a lot of options to choose precisely what we want to display.

Back then we weren't worried about where SharePoint stores these values as it will all be enriched via search pipeline, which was easy, awesome and just works.

When my colleague tried out the search with some of the classical ViewCount managed properties, they got nothing which left me scratching my head and honestly questioning my sanity. I was a bit away from hands-on role and by a bit I mean it was almost more than four years since I've been rolling my sleeve and coding stuff as I'm currently doing mainly high-level activities. With no further do I decided to look under the hood of of OTB news webpart

First thing I noticed after viewing the bundled code using pretty format feature in google chrome in the file sp-news-webpart.bundle_en-us_someguid.js when the component is about to mount a function called "updateRealNewsItems" is called, this method takes a set of items (which is the news items with the view count ) as a parameter.



With a bit of more digging by searching the "viewCounts" I manage to find an expression that verified whether the view count is needed or not which depends on the display template that you choose.  If the view count is needed firstly the code tries to update view count dataprovider information then calls refresh data.


The code continues with preparing a request , getting the view count , cache it so next time it will try to get it from the cache then add the view count to the news items which is returned by search.

That kept me wondering is it that hard to enable search pipeline to update the ViewsCount to accommodate the Site Page content so we can rely on viewCount managed property. I really have no answer to that maybe it is. Additionally I believe that if modern webparts are available on GitHub it will make SharePoint developer life easier.

Just my $0.02

Related Articles