3

My problem is quite simple.
I have a button that when clicked shows a popover.
The content of the popover is not static but depends on the response of an API.
I don't want to call that API in advance but when the button is clicked.

I want something like that: enter image description here

The property content of the popover accepts a function as input.
so I thought to call the API in it, but then I end up with the problem with asynchronous call

Here my code: https://jsfiddle.net/5x43tcja/

$('a').popover({
    content: function(){
        var result;
        fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then(response => response.json())
            .then(function(json){
                result = json.title;
            });
        return result; //The result here is undefined. But what I want is "delectus aut autem" that comes from the API.

    }
});

I tried to use async/await but still, I didn't get the result that I want: https://jsfiddle.net/jmn7abqz/

async function getData(){
    var resultFetch = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    console.log("resultFetch", resultFetch);
    return resultFetch;
}

$('a').popover({
    content: function(){
        var result = getData();
        return result;

    }
});

How can I do?


Note

I'm using Bootstrap v3.3.7

Community
  • 1
  • 1
gixlg
  • 1,193
  • 1
  • 9
  • 21

1 Answers1

0

Using show.bs.popover event

$('a').popover({
  content: 'Loading...'
}).one('show.bs.popover', function(e) {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(function(json) {
      $(e.target).popover('dispose').popover({
        content: json.title
      }).popover('show');
    });
});

https://jsfiddle.net/aswinkumar863/erkzo7as/

User863
  • 19,346
  • 2
  • 17
  • 41
  • Thanks for the help. I forgot to mention that I'm using bootstrap 3.3.7 and something seams not working with that configuration: https://jsfiddle.net/frzvL1jc/2/ – gixlg Oct 30 '19 at 14:07