How to get "updated ... ago' when rendering the results

In our index, for each object, we have:

post_modified:1523611784

How do I get at resulting search results payload to modify the data so that I can add a field time_since string based on the post_modified field?

Thanks
Eric

Hey Eric,

For that you need to use the function form of the hits template in InstantSearch.js (which I know you’re using because you made a fix on the documentation yesterday, thanks!)

import { formatDistance } from 'date-fns';

const search = instantsearch({
  appId: 'latency',
  apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
  indexName: 'instant_search',
});

search.addWidget(
  instantsearch.widgets.searchBox({
    container: '#searchbox',
    autofocus: false,
  })
);

search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item({ _highlightResult, popularity }) {
        // this is not a date, but the closest on this index
        const date = new Date(popularity + 1000000000000);
        const timeAgo = formatDistance(date, new Date());
        return `
        <article>
          <h1>${_highlightResult.name.value}</h1>
          <time datetime=${date.toISOString()}>${timeAgo} ago</time>
          <p>${_highlightResult.description.value}</p>
        </article>`;
      },
    },
  })
);

search.start();

I used date-fns here, but Moment JS or similar is also possible of course. Note that in my demo I used popularity, since it’s the only numeric attribute the index has, in your case that’s going to be post_modified without the + xxx (except maybe * 1000)

1 Like

This worked nicely. Thanks for this.

P.s., I found another error on that same page. i’ll submit another pull request today/tomorrow.