Shaun
Shaun

Reputation: 471

In react, how to pass an array of object as a query string to the endpoint url?

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

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.

Upvotes: 2

Views: 8252

Answers (1)

yondu_udanta
yondu_udanta

Reputation: 807

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)}`

Upvotes: 4

Related Questions