sachin_kumar asks how to refresh a navigation bar widget after dynamically adding items via an AJAX request. Johani explains that the issue arises because the AJAX response is delayed, causing the navigation bar to initially display the default state. Instead of relying on AJAX, Johani suggests using the Discourse application’s built-in site:main container to directly access categories, eliminating the need for an extra HTTP request and ensuring the navigation bar updates immediately. sachin_kumar confirms the solution works.
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
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}`;
}
});
});