More Efficient Way to Destructure with Conditional in ReactJs - javascript

I have this code in which we retrieve the data or get the data using useQuery. However, it fails anytime I attempt to call it using this method.
const { data: {getSubCategories} } = useQuery(FETCH_SUBCATEGORIES_QUERY);
It appears to throw an error stating that 'getSubCategories' is undefined, so I tried this method:
const { getSubCategories: subCategories } = { ...subCategoryData };
const { getChildCategory } = { ...data };
It works, but I think there is a better approach or more efficient way to destructure something with conditional syntaxes so it can't return undefined I guess I seem to notice it will take a few seconds before it will return data.
Would you mind commenting down below if you don't understand what I am trying to say or need more clarifications. Thank you.

It appears to throw an error stating that 'getSubCategories' is undefined
No, it's throwing an error when data is undefined. You can circumvent that by using a default:
const { data: {getSubCategories} = {} } = useQuery(FETCH_SUBCATEGORIES_QUERY);

If I've understood correctly you can try this: (safely destruct from the object)
const { data: {getSubCategories} } = useQuery(FETCH_SUBCATEGORIES_QUERY) || {};

Related

Access data object properties inside an object

So I have the following piece of code:
const Menus = wp.api.models.Post.extend({
url: wpApiSettings.root + 'fh/v1/menus/' + path,
});
const menus = new Menus();
console.log(menus);
menus outputs the following object:
How would I be able to access the data: { object and it's properties? It looks like it's an object inside an object.
When I do console.log(menus.attribute) that works fine, but console.log(menus.attributes.data) or even console.log(menus.attributes.success) just returns a undefined answer.
I tried doing the following:
console.log(menus.attributes['data'] also with a undefined answer.
All help is appreciated!
Try menus.attributes[0].data.
It may work. If not work, try to console this on chrome browser and share the screenshot
Probably you have an async problem here. You can try console.log the result inside a callback function.
For example you can try a similar approach like this :
import axios from 'axios';
async function getItems() {
const response = await axios.get(SOME_URL);
console.log('done', response);
return response;
}
getItems().then(items => console.log('items: ', items))
If anyone is ever wondering how to access the data, here is how I had this:
const Menus = wp.api.models.Post.extend({
url: wpApiSettings.root + 'fh/v1/menus/' + path,
});
const menus = new Menus();
console.log(menus) outputted an Object with properties that have other objects.
To access those properties inside the object, do the following:
menus.fetch().then(posts => {
const data = posts.data;
}
Now you're able to access your object properties inside the object - I hope this helps.

React / ES6 - Efficiently update property of an object in an array

I am looking for the most efficient way to update a property of an object in an array using modern JavaScript. I am currently doing the following but it is way too slow so I'm looking for an approach that will speed things up. Also, to put this in context, this code is used in a Redux Saga in a react app and is called on every keystroke* a user makes when writing code in an editor.
*Ok not EVERY keystroke. I do have debounce and throttling implemented I just wanted to focus on the update but I appreciate everyone catching this :)
function* updateCode({ payload: { code, selectedFile } }) {
try {
const tempFiles = stateFiles.filter(file => file.id !== selectedFile.id);
const updatedFile = {
...selectedFile,
content: code,
};
const newFiles = [...tempFiles, updatedFile];
}
catch () {}
}
the above works but is too slow.
I have also tried using splice but I get Invariant Violation: A state mutation
const index = stateFiles.findIndex(file => file.id === selectedFile.id);
const newFiles = Array.from(stateFiles.splice(index, 1, { ...selectedFile, content: code }));
You can use Array.prototype.map in order to construct your new array:
const newFiles = stateFiles.map(file => {
if (file.id !== selectedFile.id) {
return file;
}
return {
...selectedFile,
content: code,
};
});
Also, please consider using debouncing in order not to run your code on every keystroke.

CouchDB Document Update Handlers: Javascript

I am trying to create a generic document update handler.
I am using:
function(doc, req) {var field = req.query.field; var value =
req.query.value; var message = 'set '+field+' to '+value; doc[field] =
value; return [doc, message]; }
This works ok with simple json but not with a nested object such as
"abc":{"ax":"one", "by":"two" ...}
my curl command is:
curl -X PUT 'http://127.0.0.1:5984/db/_design/updatehandler/_update/inplace/id?field=abc.ax&value=three'
The result is a new field is created and the existing abc:{ax:one} is left
untouched.
With a simpler example:
if I have: "xyz":"five"
curl -X PUT 'http://127.0.0.1:5984/db/_design/updatehandler/_update/inplace/id?field=xyz&value=ten'
... works correctly.
I have not yet tried the generic process on "pqr":[s, t, u] yet but I guess
this may require a different design modification as well.
Ideally one wants something that works in at least the abovementioned three
cases if possible, as long as it is not too complex for it not to be worth
the effort.
Could someone possibly kindly help here or refer me to some javascript examples please.
Many thanks.
John
function (doc, req) {
function merge(nDoc,oDoc ) {
for (var f in nDoc) {
var tmpNewDoc = nDoc[f],
tmpDoc = oDoc[f];
var type = typeof(tmpNewDoc);
if (type === 'object' && tmpNewDoc.length === undefined && tmpDoc !== undefined) merge(tmpNewDoc, tmpDoc);
else oDoc[f] = tmpNewDoc;
}
}
if (!doc) {
return [null, toJSON({
error: 'not_found',
reason: 'No document were found with the specified ID or an incorrect method was used.'
})];
}
try {
var newDoc = JSON.parse(req.body);
merge(newDoc, doc);
}
catch (e) {
return [null, ToJSON({
error: 'bad_request',
reason: 'Invalid json or processing error'
})];
}
return [doc, toJSON({
doc: doc,
ok: true
})];
}"
}
Simply pass the new document to this handler. It will merge the new values to it (warning, the arrays will be overwrite). If you also want to merge array, you can either use a third party library or build your own recursive merge function.

Pulling Out Value from Within Two-Levels Deep Object

I am trying to retrieve one particular value from within a two-levels deep object data structure. First off, though, I am saving into a variable within the function, like this:
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = sessionStorage.getItem('currentUser');
console.log(userInfo);
}
}
From:
console.log(userInfo);
I get this back in the console:
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
What I want to do is specifically pull out the "_id" value here.
I tried:
console.log(userInfo.data._id);
But then my IDE is showing me an error:
'Property '_id' does not exist on type 'string'.
How do I dig out "_id" in this case?
You are accessing it wrong
Try userInfo.data._id
In the log of your object you can see by the {} notation that data is another object, so after accessing data you can access its properties just as you would with any other object.
I also see that you are getting
'Property '_id' does not exist on type 'string'.
This could mean that you never parsed the information. To find out if this is the case this should be right:
Running->
console.log(userInfo);
Returns->
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
Just after this code:
Running->
console.log(typeof userInfo);
Returns->
"string"
With your edits, I can see that this is the case.
Try:
userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);
The _id property is under the data key:
const response = {
"token":"sometoken.value",
"data": {
"_id":"8cd0362c0",
"phone":"555-4343"
}
};
console.log(response.data._id)
You can also use destructuring:
const { _id } = response.data;
console.log(_id)
or:
const { data: { _id }} = response;
console.log(_id);
So, as #jonsharpe pointed out, the key was to JSON.parse the string first. So this gets me the value I need for "_id":
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = JSON.parse(sessionStorage.getItem('currentUser'));
console.log(userInfo.data._id);
}
}
Actually your string is returned as JSON string. So you have to parse it into object using JSON.parse() if you are using js or with $.parseJSON() if you are using Jquery. So your updated code now looks like this.
var user ='{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"}}';
var k = JSON.parse(user);
alert(k.data._id);
And Fiddle is here.
Thank You

JavaScript How to access a variable from an object passed as parameter?

I have a probably really simple problem, but I can't figure it out. I'll post some cut snippets of the code that doesn't work for some reason:
//authentication_handler.js
var new_user = server.authenticated_users.add_user(new User(world));
//user.js
function User(world) {
personBody = createPlayerBody(100, 100, 8, 8, false, true, world);
exports.TheBody = personBody;
}
//player_data_handler.js
module.exports = function(server, client) {
var theUser = server.authenticated_users.find_user(client.uuid);
if (theUser != null) {
var playerData = JSON.stringify({
x: theUser.TheBody.position.x, //this line throws the error below
y: theUser.TheBody.position.y
});
server.authenticated_users.each_other(theUser, function(user) {
server.send_id_message(user.client, 5, playerData);
});
}
};
The error I get is this:
Cannot read property 'position' of undefined
I'm still pretty new to JavaScript and I don't know why the "personBody" variable doesn't get passed all the way to the "player_data_handler.js". I've tried more approaches but none of them worked. Any help is very much appreciated!!
exports is used for exporting parts of a module. If you want to add something to your object, use this:
Instead of exports.TheBody = personBody; try this.TheBody = personBody;

Categories

Resources