rails / request.js

MIT License
389 stars 28 forks source link

Append query params to url if provided #28

Closed excid3 closed 3 years ago

excid3 commented 3 years ago

If a user wants to request a url with query params, they have to build the URL with query params on their own with URLSearchParams or something similar.

For example, a dynamic country / state select you might do the following to update the state select field after choosing a country:

async updateStateSelect(event) {
  const value = event.target.selectedOptions[0].value
  const query = new URLSearchParams({ country: value })
  const response = await  get(`/addresses/states?${query}`, {
    responseKind: "turbo-stream"
  })
}

This PR adds a query option that will automatically be appended to the URL if provided. The above example can then become the following:

async updateStateSelect(event) {
  const response = await  get("/addresses/states", {
    query: { country: event.target.selectedOptions[0].value },
    responseKind: "turbo-stream"
  })
}

Both examples will make requests to /addresses/states?country=us.

I also updated the README to document all the request options a bit clearer (and documented query). Originally, I named the option params but thought query was clearer.

tabishiqbal commented 3 years ago

This is neat!

t27duck commented 3 years ago

Not sure if this is would be considered an edge case or a simple matter of "just don't do it this way", but what of the scenario where you have a URL that already has query params and you want to add on to it?

Something like this wouldn't work as expected...

const preset_url_from_some_other_process = "/addresses/states?enabled_only=true"

const response = await  get(preset_url_from_some_other_process, {
    query: { country: event.target.selectedOptions[0].value },
    responseKind: "turbo-stream"
  })

I suppose the "solution" would be "Parse out and remove existing query params from the URL and merge them with the object passed into the query option", but I at least wanted to bring this use case up.

excid3 commented 3 years ago

We can use URLSearchParams to parse an existing query string and merge them easily. Probably makes sense to add that.

It can parse a string:

let params = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
params.get("abc"); // "foo"

Then we could just merge in the query options.

I'll add that later today.

excid3 commented 3 years ago

And added!