0

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();
5
  • You can prefetch the data so that it's available before it's needed when the user attempts the first search.
    – jsejcksn
    Commented Oct 2, 2021 at 23:48
  • Not from within fetch itself. The API is what has to support the feature.
    – zero298
    Commented Oct 2, 2021 at 23:48
  • @ABDULLOKHMUKHAMMADJONOB Could you elaborate on that? I've tried something like that but it broke my filter function
    – benleem
    Commented Oct 3, 2021 at 0:13
  • @jsejcksn The response is available before the user types. It then filters results based on every letter the user types
    – benleem
    Commented Oct 3, 2021 at 0:15
  • @ABDULLOKHMUKHAMMADJONOB That actually works pretty well. Thanks, man! It has the same effect as if the api itself had the setting. I just need to find a way to make the bigger companies have priority so they don't get sliced out.
    – benleem
    Commented Oct 3, 2021 at 0:31

1 Answer 1

1

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);
    }
};
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.