Update palette dynamically (fetch configuration via API)

So here’s the problem statement:

I’m trying to fetch JSON data from an api using GET request. I’m using a function that returns a promise (fulfilled state being the desired state containing the data we need).

Due to js being asynchronous, I’m able to fetch this data in the functions that are triggered when the drag or click action is done. But not when the palette is loaded (it just returns ‘undefined’).

I’ve tried the usual methods of using async/await, etc.

If I hand over the data as a promise, it seems the palette cannot really handle that. Is there a simple solution that I’m missing?

TLDR:

I’m fetching this from a GET request:

{“generateRandomNumber”: "\n This function will generate a random number between the low and high variables respectively.\n ", “divideNumberBy2”: "\n This function divides the input number by 2.\n ", “multiplyNumberBy3”: "\n This function divides the input number by 2.\n "}

How do I possibly use the keys in this json data to define additional elements in the palette. The palette keeps loading before any of the API data is fetched it seems.

Hi @Jashanjeet_Singh!

To recap what you’d like to accomplish: You would like to create the palette dynamically, not on editor creation.

Generally speaking: This is not a concern the palette was built for. Is it possible for you to fetch the data before the editor instantiates? If that is the case the normal route (creating a palette provider, …) would work.

If you’re forced to refresh the palette (i.e. because you fetched data asynchronously) you can use the internal Palette#_update method.

:warning: Internal features, use at your own risk :arrow_down:

function AsyncPaletteProvider(palette) {
  palette.registerProvider(this);
  
  this.getEntries = function() {
    // fetch initially, once fetched
    if (!this._entries) { 
      this.fetch().then(entries => {
        this._entries = entries;
        
        // force palette refresh
        palette._update();
      });

      // initially return nothing, we did not fetch anything yet!
      return {};
    } else {
      return this._entries;
    }
}

Thanks @Nikku. It seems like I’m unable to fetch the data before the editor instantiates, i’ll have to instantiate using a callback which I’m not sure is efficient or doable. If nothing works, will do that.

Ill try and update with the force refresh method though, sounds more suited to the application.

Thanks again.