Search code examples
javascriptfetch-apitom-select

Fetching data from API to create tom-select options


i want to create tom-select option by fetching data from public API, I've successfully fetching data and store it to object, but i failed to render it to select options.

here's the code:

HTML:

<div class="p-4"><select id="select-junk" placeholder="Start Typing..."></select>
</div>

JS:

async function getCourses() {
    try {
        let res = await fetch("https://covid19.mathdro.id/api/countries");
        return await res.json();
    } catch (error) {
        console.log(error);
    }
}

async function renderCourses() {
    allCourses = await getCourses();
    result = Object.assign({}, allCourses);
    f = result.countries;
    f.forEach (country => {
        options. Push({
      iso: country.iso2,
      name: country.name,
      });
    });
}
var options = [];
renderCourses();

new TomSelect('#select-junk',{
    maxItems: null,
    maxOptions: 100,
    valueField: 'iso',
    labelField: 'name',
    searchField: 'name',
    sortField: 'name',
    options: options,
    create: false
});


please help me fix this

I've tried fetching data, store it into object, and I've checked the value using console, and here's the result:

[{ iso: "AF", name: "Afghanistan" }, { iso: "VE", name: "Venezuela" }, { iso: "VN", name: "Vietnam" }, { iso: "YE", name: "Yemen" }, { iso: "ZM", name: "Zambia" }, { iso: "ZW", name: "Zimbabwe" }]

if i sent all the result here it will too long, so i just sent some part of it


Solution

  • I think the issue here is that the below chunk of code gets executed before the promise resolves. Moving that into renderCourses solves the issue. Also, there was a small typo where you had options. Push instead of options.push:

    new TomSelect('#select-junk',{
        maxItems: null,
        maxOptions: 100,
        valueField: 'iso',
        labelField: 'name',
        searchField: 'name',
        sortField: 'name',
        options: options,
        create: false
    });
    

    This should populate the select as intended

    let options =[];
    
    async function getCourses() {
        try {
            let res = await fetch("https://covid19.mathdro.id/api/countries");
            return await res.json();
        } catch (error) {
            console.log(error);
        }
    }
    
    async function renderCourses() {
        allCourses = await getCourses();
        result = Object.assign({}, allCourses);
        f = result.countries;
        f.forEach (country => {
            options.push({
          iso: country.iso2,
          name: country.name,
          });
        });
    
        new TomSelect('#select-junk',{
        maxItems: null,
        maxOptions: 100,
        valueField: 'iso',
        labelField: 'name',
        searchField: 'name',
        sortField: 'name',
        options: options,
        create: false
    });
    
    }
    
    renderCourses();