Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add ascending or descending to url in React

I am trying to create a url based on the data I get from the user.if we consider this to be my url:

  let url = new URL('http://localhost:8080/api/movies/search/search');

I add the search fields like this:

 for (let item in data) {
      url.searchParams.set(item,data[item]); 
  }

but at the end of my url I want to add the sort type for it to look something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const url = `http://localhost:8080/api/movies/search/search?title=something&minRate=10&genre=action&sort=title,asc`;

so how should I add the last part with the comma:

,asc

to the url?

>Solution :

Based on comments on the question above…

If data is this:

{
  title: 'the',
  minRate: 2,
  genre: 'action',
  sortType: 'title',
  type: 'asc'
}

And the result you want is this:

http://localhost:8080/api/movies/search/search?title=the&minRate=2&genre=action&sort=title,asc

Then data doesn’t match what you’re looking for. It has two properties called sortType and type, and you want one combined property called sort.

Project the object into the shape you want, then use that new object to build your params:

let data = {
  title: 'the',
  minRate: 2,
  genre: 'action',
  sortType: 'title',
  type: 'asc'
};

let url = new URL('http://localhost:8080/api/movies/search/search');

// create the object you want:
let urlData = {
  title: data.title,
  minRate: data.minRate,
  genre: data.genre,
  sort: `${data.sortType},${data.type}`
};

// then add params from *that* object:
for (let item in urlData) {
  url.searchParams.set(item, urlData[item]); 
}

console.log(url);

(Note that the , character is URL-encoded by default.)

Basically, don’t change the logic to work around the data structure. Keep the logic simple and change the data structure to what you need it to be.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading