problems with variable value that initializes with wrong value not following condition - javascript

I am trying to make a method that checks if my screen is in share mode, so I made a logic that if my variable this.share is TRUE, it is shared, but if the variable this.share is FALSE, the screen is not shared.
When loading the screen, the method is called, and even though my condition is correct, the return of the variable is wrong, the return only appears as correct, after the screen loads and I perform some action like clicking a button for example, I think it may have to do with loading, or asyncs functions.
For example, the expected return is TRUE, but when loading the variable the return is FALSE and after an action the variable returns TRUE,
declaration:
this.shareKey
method to check.
this.router.events.subscribe((event: any) => {
let r = this.route;
while (r.firstChild) {
r = r.firstChild;
}
r.params.subscribe((param) => {
this.shareKey =
param.secretkey != null || param.secretkey != undefined;
});
});
I tried to do this by calling it in a service, but it didn't work.

Related

Onclick & boolean switch

I have tried to make an function with a onclick that when you click it, it will change the value from 'suspended' in true (this is about suspending a website user account)
suspended = false;
type user = User['suspended'];
function blokkeerFunctie() {
// get user & user element
document.getElementById('userInfo') && document.getElementById('blokkeren');
// blocks user when clicked
if (document.getElementById('blokkeer')?.addEventListener('click', blokkeerFunctie)) {
type user = !User['suspended'];
} else {
// deblocks user when clicked
document.getElementById('deblokkeer')?.addEventListener('click', blokkeerFunctie);
type user = User['suspended'];
}
console.log('blokkeerFunctie');
}
blokkeerFunctie();
I thought with !User i will reverse the boolean value from false in true, but that code isn't even read. ▼
'user' is declared but never used.ts(6196)
You shouldn't put event listeners in your conditional if/else in this way. Here's how I would approach what you're trying to accomplish. You will need to add types to these variables, but you'll get the basic logic here.
let User = {
suspended: true
};
let button = document.querySelector('#suspender');
function setSuspendButton() {
button.innerText = User['suspended'] ? 'Unsuspend' : 'Suspend';
}
window.addEventListener('load', () => {
button.addEventListener('click', blokkeerFunctie)
setSuspendButton();
})
function blokkeerFunctie() {
User['suspended'] = !User['suspended'];
setSuspendButton();
}
<button id='suspender'></button>
type user = creates a new type, not a value. It's unused in each branch of the if because you just create a new type, named user which shadows the type of the same name from the parent scope, which is never used by anything.
Furthermore, this line does nothing:
document.getElementById('userInfo') && document.getElementById('blokkeren');
This line gets up to two references to DOM elements, but doesn't save them anywhere, or perform any logic on them.
I think you want something more like this?
const user = {
name: 'Joe',
suspended: false
}
function blokkeerFunctie() {
// block/deblocks user when clicked
if (document.getElementById('blokkeer')?.addEventListener('click', blokkeerFunctie)) {
user.suspended = !user.suspended // toggle `suspended` back and forth
}
console.log('blokkeerFunctie');
}
blokkeerFunctie();
Working example

Search array for at least 1 match and return true

I need to test my JSON response to ensure at least 1 object contains a value of isKey:true at which point a global variable of hasKey is set to true.
I believe the SOME method would help in this situation but it seems to only test on a local level so if I console.log I get: true,false, true,true... etc
I just want a definitive true or false against the whole model.
Below you can see the basis of a working function, but I don't believe it is efficient so any advice is appreciated in improving this.
checkKeys() {
let checkTest: boolean = false;
this.modalData.columnPermissions.some(function (item) {
if (item.isKey) {
checkTest = true;
}
});
this.modalData.hasKey = checkTest;
}
You could assign the result of some directly.
checkKeys() {
this.modalData.hasKey = this.modalData.columnPermissions.some(function (item) {
return item.isKey;
});
}
You've got the right function, you're just using it wrong.
this.modalData.hasKey = this.modalData.columnPermissions.some(function (item) {
return item.isKey;
});
The 'some' function takes the return value and STOPS RUNNING as soon as one is true.
The 'every' function takes the return value and stops running as soon as one is false.

React 16.4 ComponentDidMount not respecting strict equality checks

The issue
Hello I'm running into a bit of a proplem using ComponentDidMount.
I wish to perform a network request if the value is not undefined, it will be undefined when the component mounts, the value will be passed when a user is redirected by using the state that lives inside of location which I will passed to the component usinghistory.push(route, state);
Consider the code below, I only posted the code in question since the other lines are irrelevant to the issue.
As you can see below I am making a network request if the data I'm performing an equality check on is not undefined, this indeed works when the user redirects because the value exists since the user performed an action which calls history.push(route, state); passing the route and the desired data to be passed, however if the user visits the component without first being redirected by using history.push(route,state) it will be undefined by default, in this case I'm checking to see if the value is defined or not, which should perform the equality check and not execute anything at all, instead the console throws me an error pointing to my logic for the issue, does ComponentDidMount respect equality checks for undefined properties?
componentDidMount() {
this.loadData();
if (this.props.location.state.editData !== 'undefined') {
const { asOfDate } = this.props;
const { editData } = this.props.location.state;
const { batchName, fileName } = editData;
this.getFile(asOfDate, fileName, batchName );
}
}
this is the error I am getting
Cannot read property 'editData' of undefined
at SingleTransactionContainer.componentDidMount
You are trying to access a key in an undefined object.
So you should assure that you can access the value of your key.
The best way to do it is:
(((this.props || {}).location || {}).state || {}).editData
which will return undefined if you are not receiving your props.
To resume, the problem is in your if condition and also undefined not "undefined" because if you compare
undefined === "undefined" --> false
Add below condition
if (this.props.location && this.props.location.state && this.props.location.state.editData !== 'undefined') {
const { asOfDate } = this.props;
const { editData } = this.props.location.state;
const { batchName, fileName } = editData;
this.getFile(asOfDate, fileName, batchName );
}

React setState call not updating state

I have a React setState call that is choosing to misbehave, and I can't figure out what's going on. I think I've got it narrowed down a fair bit - this is the method in question:
setShowDeleteEventModal = (value) => {
console.log('dude', value); //logs true
this.setState(() => ({ showDeleteEventModal: value }), () => {
console.log('hey', this.state); //logs state showing 'showDeleteEventModal: false'
});
};
What I've done so far:
Checked to see if it's async - it isn't, based on the problem showing up in the callback function, though I also used a setTimeout to check it;
Made sure I have state properly declared;
Checked spelling on my variables, including using Find to make sure they all show up under the same spelling;
Checked the type of value in case it was a String - it's a boolean;
Rewrote the entire implementation.
Desired behavior: showDeleteEventModal shows up true after the setState call.
Actual behavior: it doesn't.
I call this method from a button onClick in a sub-component, but since 'dude' and 'true' show up to the screen I know it's getting into here. showDeleteEventModal is a switch that controls whether a modal is displayed or not.
The part that baffles me most about it is that I have an extremely similar setup in the same file which works flawlessly. Here is the other method:
setShowOnMap = (value) => {
this.setState(() => ({ showOnMap: value }));
};
And here is the button call from the subcomponent with the prop being passed in:
<div className = "button background-red width15"
onClick = {props.switchModals}
>
Remove this event
</div>
switchModals = {
() => {
this.setShowDeleteEventModal(true);
this.closeModal()
}
}
The whole file is a little long for posting here, but hopefully this will be enough and I'm just missing something silly.
setShowDeleteEventModal = (value) => {
console.log('dude', value); //logs true
this.setState({ showDeleteEventModal: value }, () => {
console.log('hey', this.state); //logs state showing 'showDeleteEventModal: false'
});
};
Try to remove the arrow function call, for your first parameter just put the state object instead, just like above

React, check state if key pair exists depending on parameter

So I'm trying to figure out how to use kind of an all-encompassing function to reduce bloat in my application. I've got a bunch of dialog windows that are handled via state, similar to this:
toggleSettingsDialogue = () => {
this.setState({settingsOpen: !this.state.settingsOpen});
}
I'm trying to reduce this function, which is repeated for each additional dialog, into one. My thought is to pass in two parameters - one for the dialog that's meant to be opened, and another that defines the state of that dialog - either true or false.
The issue is, I'm stuck on figuring out how to check if the first parameter passed (i.e. the name of the dialog window in state) exists or not.
Let's say we've got a state with...
state = {
diagSettingsOpen: false,
diagAddItemOpen: false
}
How would I check to see if any string passed as a parameter inside the function is actually there or not, and subsequently use that key to set state if it matches?
toggleSettingsDialogue = key => {
if(key in this.state)
this.setState(({[key]: val}) => ({[key]: !val}));
}
Here's how you can check the same -
let state = {
diagSettingsOpen: false,
diagAddItemOpen: false
}
function setState(stateName, value) {
if (state.hasOwnProperty(stateName)) {
state[stateName] = value;
} else {
console.log("invalid state");
}
}
setState("diagSettingsOpen" ,true);
console.log(state);
setState("diagSettingsClose" ,true);

Categories