Home > OS >  Limiting api fetch response
Limiting api fetch response

Time:10-03

I have been working with a stock api for the past day or two, and I'm trying to make a search engine for it with a filter method. It works, but it can be slow because the initial api fetch response is an array that is about 28,000 indeces. Is there a way to limit the response I get? I looked in the documentation and there doesn't seem to be a solution through the link itself. Any help would be appreciated!

input.addEventListener('keyup', (e) => {
    const searchString = e.target.value.toLowerCase();
    const filteredCompanies = stockCompanies.filter((company) => {
        return (
           company.description.toLowerCase().includes(searchString) ||
           company.displaySymbol.toLowerCase().includes(searchString)
        );
    });
    displayCompanies(filteredCompanies);
});
const loadCompanies = async () => {
    try {
        const res = await fetch(`https://finnhub.io/api/v1/stock/symbol?exchange=US&token=${apiKey}`);
        stockCompanies = await res.json();
        displayCompanies(stockCompanies);
    }catch (err) {
        console.error(err);
    }
};
const displayCompanies = (data) => {
    var dynamic = [];
    for (var i = 0; i < data.length; i  ){
        dynamic.push(`
        <div class="listings_card">
            <h1>${data[i].description}</h1>
            <p>${data[i].displaySymbol}</p>
        </div>`);
    }
    document.querySelector('.listings').innerHTML = dynamic.join('');
};
loadCompanies();

CodePudding user response:

If api doesn't support the feature you can not. But you can eliminate the list after you receive the response. Try this way:

const loadCompanies = async () => {
    try {
        const res = await fetch(`https://finnhub.io/api/v1/stock/symbol?exchange=US&token=${apiKey}`);
        const res_data = await res.json();
        stockCompanies = res_data.slice(0, 50)
        displayCompanies(stockCompanies);
    } catch (err) {
        console.error(err);
    }
};
  • Related