Convert search string to query object (after switching to react-router v4) - url-parameters

After switching to react-router 4.0 I dumbly wasted way too much time trying to figure out how to get and set the location.search string to a regular query object.
Even after finally realizing they're not handling query params anymore (Parse Query Parameters in React Router v4) and turning to URLSearchParams I then couldn't remember how to easily extract an object from an iterator. Answer below. Hope it helps someone.

At least here's a pretty short way to do it with lodash:
const getQuery = () => {
let qp = new URLSearchParams(location.search)
_.fromPairs([...qp.entries()])
}
Oh, and now, on submitting I see: How to parse query string in react-router v4, but my answer gets the whole object.

Related

Any alternative for nesting observer in room database?

I'm quite new to programming!
I have solved the problem by following way.
Any alternative to NESTING is appreciated.
Thanks.
Using Kotlin with room database.
I get fine result by following way. But nesting for more than 3 times is not handy solution. I know I have to learn more..
observing and getting the dateString value
then passing it through second observer..
userViewModel.getUser(userId!!).observe(viewLifecycleOwner, Observer {user->
val dateStr = JSONObject(user.setting).getString("date")
payViewModel.getAllPayDate(sdf.parse(dateStr)).observe(viewLifecycleOwner,
Observer {pay->
//geting the ui related values here..
})
})

Getting "object is not extensible" when trying to add fields to result gql data objects after upgrading to Apollo client 2

When getting results from the server, usually I'm adding extra fields to the object in my Apollo Angular client, for convenience usage later on, like this:
this.apollo.watchQuery<any>({query: gql`...`})
.valueChanges.pipe(
map(result => {
result.data.sites.forEach(s => {
s.fullName = `${s.parent.displayName} - {s.displayName}`;
}
return result;
});
This used to work fine with Apollo client 1. Now I'm upgrading my code to Apollo client 2 and the latest apollo-cache-inmemory and I'm getting an error when trying to do the above:
TypeError: Cannot add property fullName, object is not extensible
I realize I can make deep copies of the objects and that would resolve, but why is this change? Is there a way to make Apollo return an extensible object like before? I have many usages of queries in my code and in almost all of them I'm adding fields to the result like the above, so it'll be a fairly big code change. Also, deep copy will have a slight performance issue.
Thanks!
Do not mutate the result, just update the fullName in immutable way.

How can I get an immutable version of an object from store.getState()?

I'm using react-redux for a project I'm working on. I noticed that when I grab an object from my store and edit it, the object in state changes without me dispatching the change (but doesn't trigger a re-render on the components attached to that reducer's object). How can I stop state from changing without a dispatch?
For example if I do:
export function changeNeonGreenColourValue(colour) {
return (dispatch) => {
var neonColours = store.getState().colours.neon;
neonColours.green = colour;
dispatch(push('./home'));
};
}
And then in the layoutComponent I log:
console.log(this.props.state.colours.neon.green)
The output is still whatever I passed into changeNeonGreenColourValue() as "colour" but the page doesn't re-render to show that change. I know to get the page to re-render, all I have to do is dispatch the appropriate reducer case but I don't want the state object being altered at all unless I have an appropriate dispatch.
Apparently the 'standard' deep copying technique for solving this is to do a JSON stringifying and parse as so: const copiedObj = JSON.parse(JSON.stringify(sourceObj)); Unfortunately if you use this on large objects that will need parsing frequently you're going to have performance issues in your app as I do, if anyone has any suggestions for this I welcome them.
edit: so both jQuery and Loadash have their own implementations of deep cloning that are supposed to be better performance-wise:
https://lodash.com/docs/#cloneDeep
I personally implemented loadash to resolve my issue and it worked fine with little to no performance issues. I highly recommend it over JSON.stringify.

KnockoutJS proper way to update observableArray AJAX

In KnockoutJS, what's the proper way to update an observableArray of JSON data each time an AJAX command is run?
Right now, I'm blanking the array using something like viewmodel.items([]), then repopulating it with the JSON data from the server. Short of using the KnockoutJS mapping plugin (which might be the only way to do this) what is the correct path?
My server logic is going to send some of the same data each time, so I can't just iterate and push the items into the array unless I want duplicates.
//// Adding how I'm doing it today ////
I'm not sure why I'm doing it this way, but this is just how I initially figured out how to update. So basically, like I said before, I get JSON data, then I pass it to something like this:
_model.addIncident = function (json) {
var checked = json.UserTouches > 0 ? true : false;
_model.incidents.push({
id: ko.observable(json.IncidentIDString),
lastTouchId: ko.observable(json.UserLastTouchIDString),
weight: ko.observable(json.Weight),
title: ko.observable(json.Title),
checked: ko.observable(checked),
createdOn: ko.observable(json.IncidentCreatedOn),
servicename: ko.observable(json.Servicename),
inEdit: ko.observable(false),
incidentHistory: ko.observableArray(),
matchScore: ko.observable()
});
};
for each node in the JSON array. As you can see, I've got some custom observables in there that get build with every passing piece of data. Maybe this is the wrong way to go, but it's worked great up until now.
An observableArray is really just a normal observable with some extra methods for array operations.
So, if you want to set the value of an observableArray to a new array, you can just do:
viewModel.items(myNewArray)
The mapping plugin can help you update the existing items in an array with any updates. In this case, your UI will only be updated from any differences.
I know I'm way too late on this one as I found myself stuck in this situation just recently. We can use a simple Javascript util function as a work-around.
If you have already marked _model.incidents as observableArray, you can do something like this when binding the returned JSON data:
eval("_model.incidents("+JSON.stringify(json)+");");
It worked for me. Hope you have created your observable like this:
_model.incidents = ko.observableArray([]);

Ajax / Json How to run an INSERT/UPDATE into mysql

Again related with my weekend project, I'm trying to learn a bit more of web-development. So I'm putting in the list of features i want to implement, some stuff i absolutely have no idea how to do.
I've been reading tutorials on how to use ajax, but i can't find a simple one, that i can copy-paste (with one or two changes) to see it work before i go into the how it works.
What I've been searching is just a simple example on an ajax function, that triggers a mysql insert or update. Anyone as a simple example on how to do this? I think it would prove a nice start to learn it. (Ajax or Json are both ok).
Correct me if I'm mystaken: I'm basing myself on this tutorial. So as obviously the client side doesn't have access to database calls, what I should do, would be something like creating a code snippet to add stuff to the database right? For example create an "addcomment.php" that can be called with xhr.open(GET, "addcomment.php?comment=mycomment", true);
Sounds like you got it right. Use Ajax to call a server side script which then does the database work for you.
A good setup is to use a framework like jQuery on the client side. This framework will encode and decode JSON automatically. On the server side you could create a class that handles all the ajax (or rather, ajaj, since we are using JSON) requests. Here is a short PHP file that shows the general idea. Add more elements to the functionMap array, and add the respective functions to the class.
class Ajaj{
private $callback = "";
private $functionMap = array( "select" => 'getIt');
function Ajaj(){
if(array_key_exists('jsoncallback',$_GET)){
$this->callback=$_GET['jsoncallback'];
}
}
function parse(){
echo "$this->callback(";
if(array_key_exists('action', $_POST)){
$action = $_POST['action'];
if(array_key_exists($action, $this->functionMap)){
echo $this->functionMap[$action];
}
}else{
echo "{}";
}
echo ")";
}
function getIt(){
return json_encode(//get the database stuff here);
}
}
$ajaj = new Ajaj();
$ajaj->parse();

Resources