2

I am working on a react app and need to build the the query string dynamically and append it to the url. The reason being is because I have a base endpoint which is same for all the links. However for some links, the api expects 2 parameters while for some it only requires 1 parameter. Depending on the link that you click, the page displays different data.

For example, I have the following 4 links on the page. Comments | View All Sequences | Review | Summary

  • Comments link: requires 2 parameters (dstrNr and rgsnId)
  • View All Sequences: requires only 1 parameter (dstrNr)
  • Review: requires only 1 parameter (dstrNr)
  • Summary: requires 2 parameters (dstrNr and rgsnId)

If I have a base url defined, how can I use the same api action and append the parameter list as an array of object to the url?

I tried the following by passing the object data as a parameter but it also send undefined object key/value pair to the endpoint as well which I don't want:

var str = [];
    for (var data in obj)
      if (obj.hasOwnProperty(data)) {
        str.push(encodeURIComponent(data) + "=" + encodeURIComponent(obj[data]));
      }
      console.log("ENDPOINT" + str.join("&")) 

Any help would be appreciated.

1 Answer 1

4

You can use querystring's stringify function instead of a custom function that exactly does what you are looking for.

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge='

https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options

In your react app, import querystring(you don't need to add a dependency as it's a Node.js's built-in module)

import querystring from 'querystring'

const url = `http://myapp.com?${querystring.stringify(queryParamsObj)}`
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Thank you so much.

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.