I'm trying to set multiple states in a for loop to be false or true depending on whether they meet the (if statement) requirement. The for loop will loop through an array of strings, each string represents a state. But I can't seem to use eval within this.setState function...
I have tried researching online but none of the solutions match my problem or what I'm trying to solve. I even tried eval(this.state.anything) = false but it still doesn't work and shows a left hand assign invalid error.
let businessState = [
"this.state.groupName",
"this.state.groupOwnerName",
"this.state.groupDesc",
"this.props.profile._id",
"this.state.businessName",
"this.state.businessDesc",
"this.state.businessRegNo",
"this.state.businessType",
"this.state.businessEmail",
"this.state.businessTel",
"this.state.businessWeChat",
"this.state.businessRegPhotoUri",
"this.state.businessSignPhotoUri"
];
var temp = ""
for (i = 0; i < businessState.length; i++) {
if (eval(businessState[i]) == ""){
temp = businessState[i]+ "Error"
this.setState({
eval(temp): true
})
}
}
As you can see from the code above, I want to evaluate the state, and if the value that this particular state holds is an empty string "", I want to set this state name + "Error" (For example, if this.state.email is empty string "" I want to set this.state.emailError to true.
Instead of this.setState({eval(temp): true}) try this.setState({[temp]: true}). The brackets will output the string value stored in temp as a variable name in setState.
This article gives a good explanation
This Stack Overflow question and the accepted answer also should help
Related
Im editing a script for fivem and Im trying to store multiple values into a variable then using an if statement to see if a player has one of the values in his inventory. So far i have this
Config.ItemVapeLiquid = 'liquid', 'liquidice', 'liquidberry'
the problem I'm having is it only runs when the player has 'liquid' on them, when they don't, it returns a nil value even if they have 'liquidice' or 'liquidberry'. what im trying to get do is:
Config.ItemVapeLiquid = 'liquid', 'liquidice', 'liquidberry'
if the player has a value from ItemVapeLiquid then
allow player to add liquid
I want it to check all the values in the variable before returning nil as it seems to be checking 1 value and returning nil if its not in the inventory
I appreciate any help!
While the first line compiles, it will ignore any unassigned values ('liquidice', 'liquidberry').
It expects three variables:
local a, b, c = 'liquid', 'liquidice', 'liquidberry'
Since that's impractical you need an array instead, as well as a function to search within that array:
Config.ItemVapeLiquid = {'liquid', 'liquidice', 'liquidberry'}
function check(array, value)
for _,v in ipairs(array) do
if v == value then
return true
end
end
return false
end
print(check(Config.ItemVapeLiquid, 'liquid'))
print(check(Config.ItemVapeLiquid, 'liquidice'))
print(check(Config.ItemVapeLiquid, 'liquidberry'))
print(check(Config.ItemVapeLiquid, 'something'))
true
true
true
false
If you plan on calling checks more often, consider transforming the array into a set instead, since this is much faster:
-- feel free to make an array-to-set function for this
Config.ItemVapeLiquid = {
['liquid'] = true,
['liquidice'] = true,
['liquidberry'] = true
}
print(Config.ItemVapeLiquid['liquid'])
print(Config.ItemVapeLiquid['liquidice'])
print(Config.ItemVapeLiquid['liquidberry'])
print(Config.ItemVapeLiquid['something'])
true
true
true
nil
Notice that a missing element is now nil, which evaluates to false and is therefore usually fine. If you really need a false value, append:
Config.ItemVapeLiquid["something"] or false
I'm trying to save just a number from a string I get from a paragraph but when I try to asign an alias to it and then check the value it returns undefined. I've tried a few solutions I found but none of those seem to work for me. These are two ways I tried (I tried another one similar to the second one but using split, had same result). The console.log inside of the 'then' doesn't show in the console, and when I try the alias after the code is when I get undefined.
cy.get('p')
.eq(1)
.should('have.text', '/[0-9]+/g')
.as('solNumber')
cy.get('p')
.eq(1)
.invoke('text')
.then((text)=>{
var fullText = text;
var pattern = /[0-9]+/g;
var number = fullText.match(pattern);
console.log(number);
})
.as('solNumber')
Please convert with + operator and return the numeric value if you want numeric type to be stored.
cy.get('p').eq(1)
.invoke('text')
.then(fullText => {
const number = fullText.match(/[0-9]+/);
return +number // text to numeric
})
.as('solNumber')
cy.get('#solNumber')
.should('eq', 42) // numeric type
});
Running your 2nd code on this,
<p>21</p>
<p>42</p>
gives the correct outcome
cy.get('p')
.eq(1)
.invoke('text')
.then((text)=>{
var fullText = text;
var pattern = /[0-9]+/g;
var number = fullText.match(pattern);
console.log(number); // logs 42
})
.as('solNumber')
cy.get('#solNumber')
.should('eq', '42') // passes
So, you need to inspect the DOM, it looks like it's not what you expect.
The first attempt you were passing a jquery element to the .should() and although some chainers change the subject yours did not so it saved the jquery element as solNumber.
The second attempt invokes the .text() which was passed to the .then() it logs the number correctly. However, you did not return anything at the end of the .then() block, therefore, solNumber should hold the entire paragraph.
This should help you out to extract the specific number and save it as an alias.
cy.get('p')
.invoke('text')
.invoke('trim')
.then(paragraph => {
const matcher = /some/
expect(paragraph).to.match(matcher) // check number is there
const indexOfText = paragraph.match(matcher) // get index of match text
return paragraph.substring(indexOfText.index, indexOfText.index + indexOfText[0].length) // return substring
})
.as('savedText')
cy.get('#savedText')
.then(cy.log) // will print out the number you seek
I'm discovering Express by creating a simple CRUD without ORM.
Issue is, I'm not able to find any record through the Model.findBy() function
model User {
static async findBy(payload) {
try {
let attr = Object.keys(payload)[0]
let value = Object.values(payload)[0]
let user = await pool.query(
`SELECT * from users WHERE $1::text = $2::text LIMIT 1;`,
[attr, value]
);
return user.rows; // empty :-(
} catch (err) {
throw err
}
}
}
User.findBy({ email: 'foo#bar.baz' }).then(console.log);
User.findBy({ name: 'Foo' }).then(console.log);
I've no issue using psql if I surround $2::text by single quote ' like:
SELECT * FROM users WHERE email = 'foo#bar.baz' LIMIT 1;
Though that's not possible inside parametrized queries. I've tried stuff like '($2::text)' (and escaped variations), but that looks far from what the documentation recommends.
I must be missing something. Is the emptiness of user.rows related to the way I fetch attr & value ? Or maybe, is some kind of escape required when passing string parameters ?
"Answer":
As stated in the comment section, issue isn't related to string escape, but to dynamic column names.
Column names are not identifiers, and therefore cannot be dynamically set using a query parameter.
See: https://stackoverflow.com/a/50813577/11509906
I'm just learning while doing ramda.js. Well, there are many ways to reach a goal with ramda, but there is on thing I do not understand.
I would like to check the input for an array of strings that all match one regular expression. I thought I could do it R.all(R.both(isString, isRegExp)), but it seems to deliver a true when the input is a number.
As expected R.allPass([isString, isRegExp]) gives a false with a number input.
But can anyone please explain me why R.all is returning a true? Or what and where is mistake (in thinking)?
Complete code:
var isString = R.is(String),
isMyRegExp = R.test(/^[a-z]+$/),
isMyRegExpString = R.both(isString, isMyRegExp),
isArrayOfMyRegExpStrings = R.all(isMyRegExpString),
isArrayOfMyRegExpStringsPass = R.allPass([isString, isMyRegExp]),
result = {
'all': isArrayOfMyRegExpStrings(9),
'allPass': isArrayOfMyRegExpStringsPass(9)
};
console.log(result);
// {
// all: true,
// allPass: false
// }
https://codepen.io/Eisenhardt/pen/PKLZqj
PS:
I know that I could shorten conditions with just the regexp, but there could be other situations where I need both conditions to be true. eg. isArrayOfNumber and sumOfNumbersOver50.
The second argument to R.all is expecting a list of values to test. Due to the way the function is implemented it is treating the 9 in your example as an empty list, resulting in a vacuous truth and evaluating to true.
I was making a calculator in Kotlin and I'm having trouble solving an issue that I'm having with while().On this particular part of the code, I'm trying to find the first operator in the equation, but I need to exclude the ones that indicate whether a number is negative - (or positive +, optional), which need to be indicated between parentheses like so: (-5)
var charay = charArrayOf('+', '-', '*', '/')
var op = 0
var reference = 0
var bol = false
while( bol == false && op != -1){
println(op)
println(bol)
println(bol == false && op != -1)
op = input.indexOfAny(charay, reference)
if (!input.get(op - 1).equals('(')){
bol = true
}else{
reference = op + 1
}
println(op)
println(bol)
println(bol == false && op != -1)
}
To test a normal equation I entered the equation 4+4 and the console looks like this:
0
false
true
1
true
false
0
false
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -2
at java.lang.String.charAt(String.java:658)
at CalculatorKt.CalculateValue(Calculator.kt:67)
at CalculatorKt.CalculateValue(Calculator.kt:108)
at CalculatorKt.main(Calculator.kt:119)
Like I suspected, for some reason, the variables reset at the end of the while(), which is the reason why it never leaves said while(). Can anyone tell me why?
Read the error. You're trying to read the character of a string at an index that doesn't exist with this statement:
input.get(op - 1)
You need to check what op is first to make sure it is found. indexOfAny returns -1 if not found in the string. Because we can't see what charay is, we can't help you further.