React-Native setState - both name and value from the same variable - javascript

Is it possible to enter only one argument to SetState that contains both the name and the value. See the example below. Is there something wrong with the brackets?
This would be handy when changing a lot of states at the same time. That is, first prepare them in one long string and execute setState only once. Thank you!
this.setState({myState: "help"}) // this works of course
whatstate='myState'
this.setState({[whatstate]: "me"}) // this too
whatstate2='myState: "please"'
this.setState(whatstate2) // but how to make this work?

// if you like to work only with strings
var whatstate = {};
whatstate['myState1'] = 'help';
whatstate['myState2'] = 'me';
whatstate['myState3'] = 'please';
// ^ this will produce an object equivalent to this
//whatstate = {
// myState1: 'help',
// myState2: 'me',
// myState3: 'please'
//}
// which you can use it to 'setState'
this.setState(whatstate);

You can call this.setState({ whatstate2 }) to achieve the same effect. This is the property value shorthand from ES6.
Reference: https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand
In case you'd like to update multiple states in one go, you can also do that like this.
this.setState({
myState1 : newState1,
myState2 : newState2
});
If the variable names are the same as the state names as mentioned previously, you can do.
this.setState({ myState1, myState2 });

Related

How to have an object key depend on another key in the same object?

I have a very simple function that builds an object and logs it.
One of the keys in the object should be depending on another key.
I think it would be much clearer when I add the code
module.exports = function (information) {
var numObj = {
[-1]: "accepted",
[0]: "fail",
[1]: "success"
}
console.log(numObj)
var ip = require('ip');
var logObj = {
UUID: information.UUID, // get from outside
FN_TIME_STAMP: information.FN_TIME_STAMP, // not sure if necessary
FN_CORRELATION_ID: information.FN_CORRELATION_ID,// get from outside
FN_REF_ID: information.FN_REF_ID, //get from outside
FN_METHOD_NAME: "docToMail", // constant
FN_STATUS_CODE: information.FN_STATUS_CODE, //get from outside
FN_STATUS_DESC: numObj[this.FN_STATUS_CODE], // depends on FN_STATUS_CODE
FN_DOC_ID: information.FN_DOC_ID, //get from outside
FN_USER_NAME: "", // empty for now, probably un-necessary
FN_APP_ID: information.FN_APP_ID, //get from outside
FN_RMT_ADDRS: ip.address(),//ip address of local machine
FN_NUM_OF_RETRIES: information.FN_NUM_OF_RETRIES, // get from outside
FN_FILETYPE: information.FN_FILETYPE, // get from outside
FN_REC_STATE: numObj[this.FN_STATUS_CODE] //depends on FN_STATUS_CODE
}
console.log(logObj)
}
I just want FN_REC_STATE and FN_STATUS_DESC to be a string depending on FN_STATUS CODE.
If its -1 i want the string to be "accepted"
If its 0 i want the string to be "fail"
If its 1 i want the string to be "success"
as it as right now i just get undefined, please help!
Thanks
Assuming that information.FN_STATUS_CODE is either -1, 0 or 1, the following solution should work.
If you change
FN_REC_STATE: numObj[this.FN_STATUS_CODE]
to
FN_REC_STATE: numObj[information.FN_STATUS_CODE]
then it should put the correct value into FN_REC_STATE.
This is because by the time that faulty line is evaluated, this.FN_STATUS_CODE hasn't been defined.
You should also change this for the definition of FN_STATUS_DESC.
Also, it looks like you may be misunderstanding what this refers to in the context of that function. It actually refers to the global object, rather than the logObj object.

How made a deep copy that can resolve a problem with a table

Im using the table material-table, where the set a new element to my object, called tableData. So that feature create an issues to my code and API because I update using Patch. I implemented a conventional and also custom deep copy of my object to avoid the table add this element to my object.
But for some reason it isnt working. This is an example of the table where you can see how it added the tableData to the example object. https://codesandbox.io/s/lx2v9pn91m Please check the console
Above I showed the real object, and in the element 5 array, appear the tableData after each render. Extra comment, the property of the table I passed to table is: data={MyRealObject.element5}
This is the struct of my real object:
MyRealObject{
element1: boolean,
element2: boolean ,
element3: Array ,
element4: Array ,
Cards: Array ,
}
Card{
Id: number ,
CardNumber : number ,
CardFormat : {CardFormatObject},
//here where appear the tableData after each render
}
CardFormatObject{
Id: number ,
CardNumberLength : number ,
CardFormatLength : number ,
Default:boolean ,
Name: string ,
}
This is the lastest custom deep copy I did and didnt work:
deepcopy(MyRealObject:MyRealObject):MyRealObject{
let salvaCard=[]
for(let i=0;i<user.Cards.length;i++){
salvaCard[i]=this.deepCardCopy(MyRealObject.Cards[i])
}
return{
element1: MyRealObject.element1,
element2: MyRealObject.element2,
element3: [...MyRealObject.element3], //I know here is not deep but isnt important now, and it isnt affected
element4: [...MyRealObject.element4],
Cards: salvaCard,
}as MyRealObject
}
public deepCardCopy(card:Card):Card{
return {
Id:card.Id,
CardNumber:card.CardNumber,
CardFormat:{...card.CardFormat}
} as Card;
}
//////////////////////////////
This are others deep code that I used and dont works, I share to save you time:
--------old solution 1(i dont like it, you can lose element if there are null)------------------------------------------------
// Cards: JSON.parse(JSON.stringify(MyRealObject.Cards)),
---------old solution 2-------------------------------------------
// MyRealObject.Cards.map(card=>{
// const {tableData,...record}=card
// return record
// }),
setState is an async function. That means you won't see the result right after calling it. You have to wait for setState to be finished. There is a callback-Parameter in setState which you can use to get the result of this.state
handleSelectedID = rowData => {
const selectedID = rowData.map(item => item.id);
this.setState({ selectedID }, () => {
// setState is async
// this is the callback
console.log(this.state.selectedID);
});
};
I changed your example-code a bit to give you an example of it: https://codesandbox.io/s/1olz33pmlj
I found a solutions, it is passsing the clone in the moment i passed the object to the table, for example:
data={MyRealObject.map(x => Object.assign({}, x))}
The issues was, that the people that create the table didnt make a clone to the data, the use the same reference, so it will be better do this to avoid problems that some one in the component didnt clone the object.
Kindly, noted, DONT used this way
data={...MyRealObject} or data={Object.assign({}, MyRealObject)}
The CORRECT is:
data={MyRealObject.map(x => Object.assign({}, x))}
Both expression look similiar but it isnot the same.

How do I set a JavaScript object's value to null

I have created this JS object from an array.
var rv = {};
$( ".part-name:visible" ).each(function( index ) {
//rv[$(this).text()] = arrayPartsName[$(this).text()];
rv[$(this).text()] = arrayPartsName[$(this).text()];
console.log(rv);
})
4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"
I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this
4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null
How can do this?
Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic
But to focus on your specific question:
Change this line
rv[$(this).text()] = arrayPartsName[$(this).text()];
to
rv[$(this).text()] = null;
Something to be aware of
If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().
var fruit = {
"pear": null, // something null
"talk": function() { console.log('WOOHOO!'); } // function
}
var apple = "app-le";
fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';
// below is not allowed, the values will be evaluated as
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';
fruit.talk();
console.log(fruit);

Cannot Read Property 'Push' of undefined - Typescript

When I try to add to an array in Typescript (wrapped in Ionic2) I get an error telling me the array is undefined even though I've declared it. I've tried declaring it using two different declarations and not found the problem. The two declarations I used are:
tracker: any[];
and
tracker: Array<any>;
The first time I try to add anything to the array and where I get the error is below. I wanted to include the whole function, just in case there was something in there that could be redefining what 'this' is:
// Answer Correctly
answerQuestionCorrectly(answer) {
let answerButton = <HTMLButtonElement>document.getElementById('answer-' + answer.AnswerId);
answerButton.addEventListener('click', (event) => {
// Increase the score
this.currentScore = this.currentScore + this.countdown;
// Set up quiz review
var correct = answer.AnswerText;
var qTrack = {no: this.questionNo, q: this.questionText, a: answer.AnswerText, c: correct}
console.log(qTrack);
this.tracker.push(qTrack);
console.log(this.tracker);
// Check for end of questions
if (this.questionNo < this.noOfQuestions) {
// Remove the old answers
var parent = document.getElementById('answers');
this.answers.forEach(element => {
var button = <HTMLButtonElement>document.getElementById('answer-' + element.AnswerId);
parent.removeChild(button);
});
// Re-init the timer
this.timer.initTimer();
// Load Next Question
this.loadQuestion();
} else {
// End the Quiz
this.endOfQuiz();
}
});
}
Those declarations only specify the type of the variable — it also needs a value. Try something like
var tracker: any[] = [];
to initialise the variable to an empty array.
You have to initialize the array before you can push an object into it.
tracker: any[ ] = [ ];
You must initialize it like this:
tracker: Array<any>=[];

How can I compare a string to an object key and get that key's value?

I want to do something relatively simple, I think anyways.
I need to compare the pathname of page with an object's kv pairs. For example:
if("pathname" === "key"){return value;}
That's pretty much it. I'm not sure how to do it in either regular Javascript or jQuery. Either are acceptable.
You can see my fiddle here: http://jsfiddle.net/lz430/2rhds1x3/
JavaScript:
var pageID = "/electrical-electronic-tape/c/864";
var pageList = [{
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
}];
var label = pageID in pageList;
$('.el').html(label);
First, your "pageList" should just be a plain object, not an object in an array:
var pageList = {
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
};
Then you can set "label" to the value from the mapping:
var label = pageList[pageID] || "(not found)";
That last bit of the statement above will set the label to "(not found)" if the lookup fails, which may or may not be applicable to your situation.
It depends kinda on the logic you want to implement. If you want to say "if object has the key, then do X, and if not, then do Y", then you handle that differently than "set label to the object's key's value if the key is there, or else set it to undefined or something else".
For the first case you do:
if (pageList.hasOwnProperty(pageID) ) {
label = pageList[pageID];
}
else {
// do whatever, maybe some error?
}
For the second case, you can just say
var label = pageList[pageID] || 'notFound';
As indicated by #Pointy, either get rid of the array or subsiture pageList[0] for pageList and pageList[0][pageID] for pageList[pageID] above, if you need to keep the array.

Categories

Resources