parsing location.search object to find query params - javascript-objects

I'm trying to figure out where in the location.search object the query params are:
Code:
const params = new URLSearchParams(this.props.location.search);
console.log(params);
URL:
http://localhost:3000/detail/8?abc=20
Chrome Console:
Where should I traverse to find params in the URLSearchParams object tree in the Console?
Also is there a find or search feature in the Console that lets me figure out the location of something? It's like an endless tree.

There are various ways of accessing the parameters via the API, I'm guessing get, getAll, or keys are what you need. The reason you don't see values directly in the console is that these are methods, not attributes, so they need to be executed for you to see the actual data.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
This question isn't really a ReactJS question, unless you're having trouble with the this.props.location.search object itself, in which case you should post its source/parent component.

Related

How to pass key value pairs as parameters in Route Path?

The react documentation says that the match object contains a param property assigned to an object with Key/value pairs parsed from the URL corresponding to the dynamic segments of the path.
When I try to pass key value pairs as parameters, I only get the key, but the value is always undefined.
<Route path="/location:color?" component={Location} />
If I do this, and then in the Location component, I console log props.match, I get the match object, but when I open it, I get this: params: {color: undefined}.
How do I pass value too?
Also, I feel like I'm misunderstanding something about these path parameters, because what exactly is the point of them? If I wanted to pass any value to any component, I can just use props. What is the purpose of these path parameters?
For all complex data structures, I recommand parsing to string and deserialize at the other end. it may be a good practice if everyone in your team is doing it this way.
Example :
KeyValuePair : <Color,Blue>
Parse it to string : "\"Color\",\"Blue\"
The idea of using path="/location/:color?":
is to fetch/navigate to a page according to its id to get information
For example, I want to get student information on the page, first, it goes to URL www.location/studentId it will take the student id to know which student to view on the page.
In your case, you get undefined because you didn't pass any color value, so you need to pass the value to navigate as follow:
- change `<Route path="/location:color?" component={Location} />`
to `<Route path="/location/:color?" component={Location} />`
- To navigate use `this.props.history.replace("/location/" + this.props.color);`
Please read this article it will give you more ideas about react-routesreact routes Article
or React routes documentation

What is the correct way of setting React State with Oboe.js?

I am new to both React-JS and Oboe.js. I am trying to speed up loading of some JSON data by using Oboe to stream the results. Unfortunately I am unable to do an update state in the function block. So I try to call another function that does the stateSet. Below is a method I have tried but doesn't work. It errors out a mapping function that uses search-results to render it in a table.
var that = this;
oboe({
url: //url,
method: 'POST', // optional
body: //POST-DATA, // optional
})
.on('node', '*', function(things){
that.updateState(things);
// This callback will be called everytime a new object is
// found in the foods array.
console.log( 'Go eat some', things.id);
});
updateState = (props) => {
this.setState({search-result: props});
}
What I am not sure about is the right way of updating a state with oboe.js and React?
Is there a better library to use for streaming JSON data into React?
Recommended approach
If you have the ability to change things server-side, then I would not recommend using Oboe for this. Oboe is useful if your only alternative is to load a large JSON object and you would like to access that data before the whole thing can be parsed.
The best way to optimize loading a lot of data on a client is to send less data at a time and to make multiple requests. A web-socket is the best approach, and Socket.io is a good tool for doing that.
If you need to use Oboe
I'm working to put together an example of oboe.js + react for you to look at, though it's tricky as much of the activity of Oboe happens outside the React lifecyle. I'll update this answer with that example 👍

How to pass parameter in url and call api with it?

I am using ReactJS and I have filters in post page. What I want is that when I click on filters it should pass parameters in URL and call the API on the basis of it.
Can anyone suggest an example some for it?.
E.g. history.push ({
pathname:'/users',
search:'?filter1=value_filter1'
})
in above code how to add multiple values and remove values
If i understand,you would like to update your url by adding query parametres based on filters.
The simplest way to add query params is through the push method of hasHistory by passing an object as parametre .
E.g.
history.push ({
pathname:'/users',
search:'?filter1=value_filter1'
})
It also possible to pass an object into the search key with params
For more information about how it works,you can go into the following links : Make it easier to add query parameters or this youtube video Query Strings with React Router

Pass (hidden) data with $location.url

I'm getting a server response on a request that includes the following:
redirect_url
job_name
I'm using angular's $location.url(redirectUrl) to navigate to the redirect url, which may have query string parameters. I'd also like to pass it the job_name for use by the next state, but even the ugly solution of tacking it onto the search params (with $location.url(redirect_url).search(job_name) doesn't work if redirect_url already HAS search parameters.
How can I pass data to a new state if I don't have the state's name, only the url? Do i have to parse it out?

How to deal with query params in react + react-router + flux

I'm trying to replace a Backbone.Marionette App to React and am facing difficulty thinking about query params. I think I'm missing a really simple peace in understanding this pattern so I apologize if this question is totally nonsense. I would appreciate any support or just pointing me to some direction that I can google more specifically.
There's a /users page which lists users and you can filter the users via search bar. So if you want to filter the users which contain 'joe' in their username, I would make a request to the server with query params like /users?username=joe. In addition I am able to paginate by adding a page parameter, too (/users?username=joe&page=1).
If I only think about the functionality, the flow would probably be
The Client inserts joe to the input element and clicks Search.
Clicking the Search button fires an Action (like Action.getUser).
The Action makes a request to the server and receives the results
The Dispatcher dispatches a function with the results payload to whomever (usually the Store) is interested in the Action.
The Store's state changes with the new result received by the Action
The View (Component) re-renders by listening to the Store's change.
and it works as expected. However, I would like the Client to be able to bookmark the current filtered result and be able to come back to the same page some time later. This means I will need somewhere to save explicit information about the search term the Client made, which is usually the url (am I right?). So I will need to update the url with query parameters to save the search term (/users?username=joe&page=1).
What I'm confused is where and when to update the url? What I can come up with right now are the 2 options below - and they don't seem to be clean at all.
Option 1
The Client inserts joe to the input element and clicks Search.
Clicking the Search button fires a transition of the ReactRouter with the new query params (/users?username=joe&page=1).
The View (Component) receives the new params via this.props.params and this.props.query.
The View (Component) fires an Action like Action.getUser depending on the query params it receives - in this case username=joe&page=1.
after this, it is the same as above
Option 2 (only 6 is different from what I explained above)
The Client inserts joe to the input element and clicks Search.
Clicking the Search button fires an Action (like Action.getUser).
The Action makes a request to the server and receives the results
The Dispatcher dispatches a function with the results payload to whomever (usually the Store) is interested in the Action.
The Store's state changes with the new result received by the Action
The View (Component) re-renders by listening to the Store's change. And somehow (I don't know how, yet) updates its url depending on its props (like this.props.searchusername, and this.props.searchpage)
What is the best practice on handling query params? (or this may not be specific to query params)
Am I completely misunderstanding the design pattern or architecture? Thanks in advance for any support.
Some articles I've read
Any way to get current params or current query from router (outside of component)?
Async data and Flux stores
Make it easier to add query parameters
React Router and Arbitrary Query Params: Page Refreshes Unintentionally on Load?
Add default params?
I would consider best practice to be the submit button only setting the location query (username). The rest should be taken care by the main react component that is assigned as router component. By this, you can be sure that anytime one revisits or shares the url, they can get the same results. And this is very generic too.
Something like this:
let myQuery = this.props.location.query;
if (myQuery.username) {
let theUser = myQuery.username;
this.setState({
userName = myQuery.username
});
} else {
this.setState({
userName = false //Show All
});
}
And then use this state "userName" to send to the server to search with. By this way, you will not need to iterate the code of the component that takes care of listing users since server already sends the relevant data.
In my experience with using location queries in React, I have been very content with their reactivity cycles and performance. I'd highly recommend keeping every different app state in relevance with the url.
Not entirely sure what you mean by
this means I will need to update the url to save the information (/users?username=joe&page=1).
You will probably have a similar structure to this.
TopContainer.jsx
-- Users.jsx
-- a list of User.jsx
Usually TopContainer will watch all the stores and if anything changed, pass it down to users.jsx. That way in Users.jsx, you can simply render this.props.users without worrying about any reRendering.
The search users actions usually happens in TopContainer's componentWillMount event, and you the page will listen to UserStore. That's a good place to throw in any query params. Something like this would work
componentWillUnmount() {
let searchTerm = router.getCurrentQuery().searchTerm;
UserActions.searchUsers(searchTerm)
},
The page doesn't really care if the url has a query params or not, it just dumbly shows whatever in the user store.
Then when the search finishes, Users.jsx will be reloaded and show the correct results

Resources