0

Normally I use these function for first search parameter.

history.push({
    pathname: props.location.pathname,
    search: "nice=yes"
})

and after these history.push link looks like this -> x.com/title?nice=yes

But I can't add more search query. When i try to add new key only old key change. For example my link is x.com/title?nice=yes and i add second search when page change, query looks like this;

history.push({
    pathname: props.location.pathname,
    search: "page=10"
})

But it changes first parameter.

I want add multiple parameters like this: x.com/title?page=10&nice=yes

Jay Vaghasiya
  • 1,661
  • 2
  • 8
  • 23
MehmetDemiray
  • 758
  • 4
  • 10
  • 25

3 Answers3

2

if you have multiple parameters you have to put them in an object first :

const params = {
    page: 10,
    nice: "yes",
    size: 20,
    ...
}

then serialize them with this function :

const serialize = obj => Object.keys(obj)
                             .map(key => `${key}=${encodeURIComponent(obj[key])}`)
                             .join('&')

like this :

history.push({
    pathname: history.location.pathname,
    search: serialize(params) // => search: 'page=10&nice=yes&size=20&...'
})
Hayi
  • 6,308
  • 23
  • 73
  • 126
0

Currently, when you push the second time, you add the following query parameter ?page=10 to the pathname x.com/title

pathname: props.location.pathname, ==> x.com/title

If you want to add a new query parameter you have to check if there is a query parameter using a foreach on this.props.location.query, and if there is one, you add it to the pathname

That will look like this :

let currentPathname;

this.props.location.query.foreach(qparams => {
   currentPathname + qparams
});

history.push({
  pathname: this.currentPathname,
  search: "page=10"
})

There is a question related

Benjamin Barbé
  • 448
  • 5
  • 18
0

Create a string with multiple parameters

history.push({
    pathname: props.location.pathname,
    search: "page=10&nice=yes"
})
Jay Vaghasiya
  • 1,661
  • 2
  • 8
  • 23