Demo: Dyamically Fetch Data

In this example, we populate the Typeahead component with JSON data that's dynamically fetched from an external source via the getSuggestions hook.

Also, this demo caps the max # of search results to display at 5.


{% include "@bolt-components-form/form.twig" with {
  children: include("@bolt-components-typeahead/typeahead.twig", {
    attributes: {
      class: [
        "js-typeahead-hook--dynamically-fetch-data"
      ]
    },
    max_results: 5,
    input_name: "q"
  }),
  attributes: {
    action: "https://www.pega.com/search",
    target: "_blank",
    method: "GET"
  }
} %}

// NOTE: make sure you're running this code through a tool like Babel before shipping for cross browser compatibility!
const dynamicTypeaheadDemo = document.querySelector(
  '.js-typeahead-hook--dynamically-fetch-data',
);

const setupEventHandlers = () => {
  // note: make sure to let Typeahead know when the data fetched is ready
  dynamicTypeaheadDemo.on('getSuggestions', async value => {
    return await new Promise(async resolve => {
      await fetch('/build/data/typeahead.data.json')
        .then(function(response) {
          return response.json();
        })
        .then(function(data) {
          return resolve(data);
        });
    });
  });

  dynamicTypeaheadDemo.on('onSelected', (element, event, suggestion) => {
    const exactMatch = element.items.filter(
      item => item.label === suggestion.suggestionValue,
    )[0];

    function navigateTo(url) {
      if (window.location !== window.parent.location) {
        const win = window.open(url, '_blank');
        win.focus();
      } else {
        window.location = url;
      }
    }

    if (exactMatch && exactMatch.url) {
      if (exactMatch.url) {
        navigateTo(exactMatch.url);
      } else {
        navigateTo(`https://www.pega.com/search?q=${itemSelected.label}`);
      }
    } else if (suggestion.suggestionValue !== '') {
      navigateTo(`https://www.pega.com/search?q=${suggestion.suggestionValue}`);
    }
  });
};

if (dynamicTypeaheadDemo) {
  if (dynamicTypeaheadDemo._wasInitiallyRendered) {
    setupEventHandlers();
  }

  dynamicTypeaheadDemo.addEventListener('ready', e => {
    if (e.detail.name === 'bolt-typeahead') {
      setupEventHandlers();
    }
  });
}