0

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!

2 Answers 2

1

If I understand the question correctly, you can iterate over your array easier via .map and then merge the array into a single string using .join():

const data = [{url: "apple"}, {url: "banana"}]
const url = `http://myurl.com?${data.map(item => `filter=${item.url}&`).join('').slice(0, -1)}`
console.log(url)

Note that .slice() ist needed to cut the last & character off the string.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if my question wasn't clear! The url is a little more complex and I think that URLSearchParams is overall a simpler approach (the code looks cleaner and works - I've posted an answer with my solution). Thank you anyway for trying to help me!
0

So I think my previous approach wasn't the best.

It seems as the URLSearchParams-API is a simpler approach when working with urls and params - at least with this solution the code works and looks cleaner.

Here is what I have now:

const getInfo = async (filters, searchTerm) => {
    let url = "/api/productInfo?";
    let params = new URLSearchParams();

    if(searchTerm.length !== 0) {
      //logic
    }; 
  
    if(filters.length !== 0) {
      filters.forEach((filterItem) => {
        params.append("filter", filters.categoryUrl);
      });
    };
  
    try {  
      url = url + params;
      console.log("url", url);
      ...
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.