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);
Related
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.
Hello so I am creating a filter search and I 'm trying to collect all the key (tags) that the user press, inside an array, however every time that a new value is push it does override the entire array. So I tried a couple of things, like spread syntax, concat, etc. But with no luck.
So my action looks like this:
const setCurrentFilters = async (context, payload) => {
if (payload) {
context.commit('setCurrentFilter');
}
}
My state
state:{
filters: JSON.parse(sessionStorage.getItem('currentFilters') || '[]'),
}
The mutation
setCurrentFilter(state, payload) {
state.filters.push(payload);
sessionStorage.setItem('currentFilters', JSON.stringify(payload));
}
And my getter
currentFilters(state) {
return state.filters;
},
Thank you in advance for any help : )
This is simply because you set const filters = []; which means that the next condition if (filters.length) will always return false (as you just created this array) and therefore the else statement will execute.
in the else statement you basically push the new payload to the empty array you just initialized - which makes your array always hold only the new value
i believe that you just need to remove the const filters = []; line, and access the filters property that exists in your state
I want the user to have the option to add more stepTypes, stepCodes and properties. He can add an stepCode with an existing StepType, or with a different stepType, so, the object would like similar to this:
You see? In the stepType called 'guide', I have 2 stepCodes (G019, G040). In the stepType called 'success', I have just one (S003), and so on. Since I'm newbie with js and even more with objects, I'd like you guys to help me creating a function that checks if the stepType already exists, and then adds another stepCode to it (with its properties). And, if it doesn't exist yet, I want this function to create this new stepType, with the stepCode and its properties.
Currently, my code looks like this:
const checkStep = () => {
if (!Object.keys(procedures).length) {
let proc =
{[key]:
{
[stepType]: {
[stepCode]: {
[language]: stepText,
timeout,
nextInstruction,
}
}
}
}
setProcedures(proc)
}
else{
Object.entries(procedures).forEach((p, k) =>{
...
})
}
}
I call this function everytime the user clicks the "Add another step" button. The first part checks if the object already exists, and, if it doesn't, it creates the object with its key and so on (this part is working). What I don't know how to do is the ELSE part. I think we have to check if the stepType already exists in the object called procedures, but I don't know how to do it. I don't know how to put the stepCode and properties inside the existing object(procedures) either. Maybe I create a variable and do like: setProcedures (...procedures, variable). I don't want to lose the content I have in the procedure, just to add more content to it in the way I explained you.
P.S.: All the variables (stepType, stepCode, language, stepText, timeout, nextInstruction) are an useState. When the user writes anything in the input text field, I set the specific variable with the e.target.value.
Thank you.
You can do the loop on the each keys and if it matches then add to existing data or create a new stepType and add.
var newStepType = "test", stepCode="test1", language ="en", stepText="hello", timeout=9, nextInstruction="new ins";
Object.keys(procedure.DOF0014).forEach(key => {
//if newStepType matches insert stepCode. eg: stepType is "guide"
if(key === newStepType) {
procedure.DOF0014[key] = { ...procedure.DOF0014[key], ...{[stepCode]: {[language]: stepText,timeout,nextInstruction}}}
}else{
procedure.DOF0014 = {...procedure.DOF0014, ...{[newStepType]:{[stepCode]: {[language]: stepText,timeout,nextInstruction}}}};
}
});
Try this. I didnt tested code. But hope it works. I am sharing the idea how to do.
Object.keys(procedure).forEach(codes => {
Object.keys(procedure[codes]).forEach(key => {
if(key === newStepType) {
procedure[codes][key] = { ...procedure[codes][key], ...{[stepCode]: {[language]: stepText,timeout,nextInstruction}}}
}else{
procedure[codes] = {...procedure[codes], ...{[newStepType]:{[stepCode]: {[language]: stepText,timeout,nextInstruction}}}};
}
});
})
could you please tell me how to get updated value from state.here is my code
https://codesandbox.io/s/cool-ives-0t3yk
my initial state
const initialState = {
userDetail: {}
};
I enter 10 digit number on input field and press enter and update the user detail like this
const onSubmit = async values => {
if (values.mobile.length === 10) {
setUserDetail({ msdin: values.mobile });
console.log(userDetail);
}
};
setUserDetail({ msdin: values.mobile }); here I am updating my userdetail .
and try to console the update value like this
console.log(userDetail); .it is showing currently undefined.but expected output is {msdin:'9999999999'} (or whatever it is type in input field)
The problem is that you are using hooks and it's not synchronised, it's async. Therefore, accessing the detail immediately after setting the value will not be possible. If you want to access the data there, you will have to use values.mobile
The state will keep the last value until the next render is called.
You can see this information on react-hooks document
During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.
So, the code should look like:
const onSubmit = async values => {
if (values.mobile.length === 10) {
const newUserDetailState = { msdin: values.mobile }
setUserDetail(newUserDetailState);
// do your stuffs with the newUserDetailState instead of userDetail
console.log(newUserDetailState);
}
};
The state setter setUserDetail is async, that means that the new state value won't be available immediately.
To see if the state update use useEffect like this :
useEffect(() => {
console.log('useEffect -> UserDetail : ', userDetail);
}, [userDetail]);
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.