I'm trying to fetch data based on the url.
Everything works except on: let urlFilters.
What I'm trying to do:
- iterate over the array: filters (if it's not null)
- save output in: let urlFilters
By now, the iteration seem to work. When I console.log(urlFilters) I get key-value-pairs like "filter=orange" or "filter=apple?". The problem: only the last key-value-pair is saved and thus used for the url.
My question: how can I save all the key-value-pairs from the iteration and use them all in the url?
const getInfo = async(filters, searchTerm) => {
let url = "";
let urlBasis = "/api/productInfo?";
let urlSearchTerm = "";
let urlFilters = "";
if (searchTerm.length !== 0) {
...
} else {
...
};
//problem
if (filters.length !== 0) {
filters.forEach((filterItem, index) => {
urlFilters = `filter=${filterItem.categoryUrl}${index === filters.length -1 ? "" : "&"}`
//console.log(urlFilters) -> "filter=orange" or "filter=apple&"
});
} else {
urlFilters = ""
};
try {
//problem urlFilters: shows only the last key-value pair
url = urlBasis + urlSearchTerm + `${searchTerm.length !== 0 && filters.length !== 0 ? "&" : ""}` + urlFilters
} catch (err) {
console.log(err);
}
};
I already tried to use .map instead of .forEach. I also tried to use the spread operator. But it didn't work and I'm a little stuck. Any suggestions (also for code improvement) are appreciated. Thanks a lot!