How to refresh a particular widget after getting data from ajax

Hello I have been trying to implement a custom navigation bar for my discourse website and below is my code now

  $.ajax("/categories.json").then(
    (data) => {
      data.category_list.categories.map((val)=>{
            api.addNavigationBarItem({
            name: val.name,
            displayName: val.name,
            title: val.name,
            href: `/c/${val.slug}`,
            forceActive: (category, args, router) => {
                return router.currentURL === `/c/${val.slug}`;
                }
            })              
        })
        
    }
  );

Now I have to manually go to other link for it to show up the newly added nav items how can I reload the navigation bar after getting values from ajax
Thank You

2 Likes

The issue here is that your code to add the new nav items only fires once the ajax request is resolved. So, in the very few milliseconds it takes to do that, the default (unmodified) nav is displayed. That’s why you see it on the initial page view.

Once you navigate to another page, the request will have resolved, and your changes would then start working.

To answer your question, yes, you can conditionally rerender a component.

That said, it’s not really the answer you’re looking for. You don’t even need the ajax request. You can get the list of categories from the application directly. This fixes your problem and saves you an extra HTTP request. Try something like this (based on your code).

// lookup categories
const categoryList = api.container.lookup("site:main").categories;

// add a nav item for each category
categoryList.map(val => {
  api.addNavigationBarItem({
    name: val.name,
    displayName: val.name,
    title: val.name,
    href: `/c/${val.slug}`,
    forceActive: (category, args, router) => {
      return router.currentURL === `/c/${val.slug}`;
    }
  });
});
1 Like

Thank you Joe It is working very well now

2 Likes