Caching page data for preview mode

2024/08/28 10:25 AM

We found an issue where the 'preview' mode for pages wasn't showing the most recent data. Looked into it and found it was an issue with the caching only clearing when changes were published rather than saved.

I added in the 'allstates' prefix to the cache key to resolve this but it now means the cache on the live site is also clearing when something is saved rather than published.

Example of how we're caching below:

	return await ProgressiveCache.LoadAsync(async (cs) =>
{
    cs.CacheDependency = CacheHelper.GetCacheDependency($"webpageitem|allstates|byid|{webPageItemID}")
	var queryBuilder = new ContentItemQueryBuilder()
        .ForContentType(NewsPage.CONTENT_TYPE_NAME, queryParameters => queryParameters
            .ForWebsite(WebsiteChannelContext.WebsiteChannelName)
            .WithLinkedItems(1)
            .Where(w => w.WhereEquals(nameof(WebPageFields.WebPageItemID), webPageItemID))
            .TopN(1)
        );
    var pages = await Executor.GetWebPageResult(queryBuilder, WebPageMapper.Map<NewsPage>, new ContentQueryExecutionOptions { ForPreview = WebsiteChannelContext.IsPreview, IncludeSecuredItems = false }).ConfigureAwait(false);

    return pages.FirstOrDefault();
},
new CacheSettings(1440, WebsiteChannelContext.WebsiteChannelName, nameof(NewsRepository), nameof(GetNewsPageAsync), $"PageID-{webPageItemID}", $"Preview-{WebsiteChannelContext.IsPreview}")).ConfigureAwait(false);

Is there another recomended way of handling caching so that the live site cache only refreshes when a change is published, but the cache for the preview mode updates whenever something is saved?


Environment

Answers

2024/08/28 1:51 PM
Answer

Hey Alex, please check the WebsiteChannelContext.IsPreview flag, and if it is true, skip caching. I recommend checking out my blog post on data retrieval in XbyK, specifically the code sample under the "The ContentRepositoryBase.cs file" heading.

To answer this question, you have to login first.