Home > Software design >  I Want To Print all the api result to page
I Want To Print all the api result to page

Time:12-23

I Have This Result Of API

I Want To access all the values inside this array but when i try for loop or forEach loop its just print the last 9th item of the array

Just Like This

const options = {
        method: 'GET',
        headers: {
            'X-RapidAPI-Key': 'API-key',
            'X-RapidAPI-Host': 'contextualwebsearch-websearch-v1.p.rapidapi.com'
        }
    };
    
    fetch(`https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI?q=${query}&pageNumber=1&pageSize=10&autoCorrect=true`, options)
        .then(response => response.json())
        .then(response => {
            
             for(let i = 0; i < response.value.length; i  ){
                result = `
                
                <h3>${response.value[i].title}</h3>
                
                `;
                document.getElementById("result").innerHTML = result;
             }






            //  response.value.forEach(res => {
            //      result = `
            //      <h3><a href="${res.url}">${res.title}</a></h3><br><a href="${res.url}" color="#bdc1c6">${res.url}</a><br>
            //      <p>${res.snippet}</p>
            //      `
            //      document.getElementById("result").innerHTML = result;
            //  ;
            //  });
            console.log(response.value)})
        .catch(err => console.error(err));
})

this is what i was trying please tell me if my code is wrong or give me an appropriate answer

CodePudding user response:

this is probably your problem:

document.getElementById("result").innerHTML = result;

here you are overriding the value inside after each loop, that's why you will only find the last value displayed.

you can use the = operator to increment the HTML to the existing one inside your result element.

document.getElementById("result").innerHTML = result;

  • Related