How to store object on URL query string
Asked Answered
C

0

7

I am developing a generic search component on React that puts it's filters, current page and some other params on the URL query string (after the ?).

I currently use the URLSearchParams to transform the query string to js objects and back to query string, as the react-router-v4 expects

The point is that I need to store an Object within the query string, so I can differentiate the search filter (that can have multiple fields) from other params.

I see that I can transform a object to JSON, and store everything on a filter param, or I could store the object using dot notation (?filter.name=foo&filter.tag=bar) or even a square brackets notation (?filter[name]=foo&filter[tag]=bar) and treat them accordingly when reading them from the url.

I am tending to choose the JSON notation, but Is there any problems with this approach? Should I know beforehand any limitations? Is there a better way to do it?

Coolant answered 11/6, 2018 at 15:50 Comment(4)
Hello Murilo, you helped me last week with a question I had for React so I thought I give you my input maybe of some assistance? What I do to pass information to the URL is I use Link to pass the variables and then in my Routes, I pass in the param for that specific Route. I can show you an example if you want? I'm not sure if it'll be of any assistance though. I use it all the time to pass information to other Routes which I have access to in the future.Perigon
Good to know that I were helpful :) So, I already use the Link, and sometimes the push() method (when a api call return and then I redirect to somewhere), and setting the search param works nicely. The problem here is that on the search string I want to store an entire JS ObjectCoolant
hmm.. I'm not too sure myself if you can pass json into the URL. I believe you would need to convert that object into a string so that the URL can read it. what I would do is if it was an object, I would parse it using JSON.stringify and pass in the string so the url could read it and if you need to use it in your view, I would parse it out again using JSON.parse to parse it back into an object.Perigon
yes! that's my first idea. I've seen other 2 options, and I don't know if there are some problems with any of them. I would like to hear from someone that have already done it if there is any problemCoolant

© 2022 - 2024 — McMap. All rights reserved.