React Native If Statement Not Functioning properly with State - javascript

I have created this function in react native:
confirmOTP(){
console.log(this.state.otpEntry)
console.log(this.state.sixDigitauth)
if (this.state.otpEntry === this.state.sixDigitauth){
this.setState({
modalVisibility: false
})
console.log ("authenticated")
}else{
console.log ("incorrect OTP")
}
}
Although the function console logs both this.state.otpEntry and this.state.sixDigitauth and the text in them matches, I still end up getting a console log of "incorrect OTP". This means that the if statement is unable to match both states.
464042 464042 incorrect OTP
Both data types are text:
this.state = { sixDigitauth: '', otpEntry: '', }
Any idea why?
thanks in advance

It appears like you have a mismatch of datatypes, and since a triple equal sign attempts to match variables on their content, as well as their type - it returns false, hence your query fails.
You have a couple of options:
Add a + sign in front of the variables. It will convert them to a Number type:
confirmOTP(){
if (+this.state.otpEntry === +this.state.sixDigitauth) {
// do something
} else {
// do something else
}
}
Replace a === sign, with == sign. I don't recommend it, but it will technically solve the problem.
confirmOTP(){
if (this.state.otpEntry == this.state.sixDigitauth) {
// do something
} else {
// do something else
}
}
You could also make sure they're in appropriate datatypes, at the moment of updating the state:
constructor(props) {
super(props)
this.state = {
otpEntry: +props.otpEntry
sixDigitauth: +props.sixDigitauth
}
}
Make sure to catch up on some theory.
equations:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
unary plus:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus

Related

Why is split() function failing on only one condition but not another

Context
I'm converting a create-react-app app to nextjs. Most of my work is ensuring existing components work for SSR.
I have one component that is throwing a build error of:
Error: text.split is not a function
For the final condition of this function:
function createRender(text, type, size, paragraphs, inline, nogap, url) {
let renderObj;
if (text) {
// if text is an array, return a string of the array
if (text instanceof Array) {
text = text.join('');
}
if (type === "title") {
renderObj = <h2>{text}</h2>
} else if (paragraphs === true) {
renderObj = text.split('\n').map((paragraph, index) => {
if (paragraph !== "") {
return <p>{paragraph}</p>
}
})
} else {
renderObj = text.split('\n').map((paragraph, index) => {
if (paragraph !== "") {
return <p >{paragraph}</p>
}
})
}
}
return renderObj
}
Question
This split request (as far as I can see) is identical to that in the condition preceding it. Which doesn't throw an error.
This isn't an error occuring at runtime when something that isn't a string has been passed. This is a build error.
What am I missing that might be causing text in this one condition to throw this error? In my previous experience with javascript, I'd only get an error when running and a variable that wasn't a string had an attempted split. Here, a variable hasn't even been sent yet.
Also, why isn't it causing an error in the condition above it, with the exact same code? If I remove the final 'else' condition, I don't get the error.
Caveats
Ignore the logic in the conditions, I've removed some fluff to make this reproducible in its smallest form.
I'm using nextjs 13 and its app folder. I'm brand new to nextjs and saw this is an experimental features so I'm unsure if something exterior from this function is causing the issue.
Update 1
I've found that the error isn't thrown if I add a defined condition to the final else. As in, if I replace:
} else {
renderObj = text.split('\n').map((paragraph, index) => {
if (paragraph !== "") {
return <p >{paragraph}</p>
}
})
}
with
} else (any variable === anything) {
renderObj = text.split('\n').map((paragraph, index) => {
if (paragraph !== "") {
return <p >{paragraph}</p>
}
})
}
The condition definition is arbitrary. I can put size === 'melon' and it no longer throws an error.
I was too used to client-side-rendering and was still using the perspective that functions and variables only throw errors when building if there's bad code.
Whereas as this function is built for SSR, it's being passed actual real variables and is throwing an error in the same veign as I would have been familiar with during runtime on CSR.
So the problem was catching a bad variable that was meant to be a string but wasn't.

Validate phone number on React.js

I'm trying to validate the phone field, to get all letters and dots with the code below.
validatePhone = () => {
const sanitizedPhone = this.state.phone.replace(/\D/g, '');
if (sanitizedPhone.length >= 10 && sanitizedPhone.length <= 11) {
this.setState({ phone: sanitizedPhone });
return true;
}
toast.error('Invalid phoneNumber.', {
position: "top-center",
autoClose: false,
closeOnClick: true,
});
return false;
}
When i trying console.log(sanitizedPhone) with dots in input like 11.97.4.4.51234 i get 11974451234 but after this, on console.log(this.state.phone) i get the older number 11.97.4.4.51234
From react docs:
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.
This is why you don't see your change right after you're using setState.

node.js code does not read else condition when user does not specify a search argument (only reads if condition)

Currently, my if/else statement does not work correctly as it never goes to the else portion of my code. The node app takes in an argument (process.argv[3]) and uses that to pick the API to call. process.argv[4] is used to specify what to search (example "Yesterday") and works correctly if argument is provided. However, I want to have a default search if user leaves that argument blank. I'm unsure of why it never goes to the else portion of the code.
I'm new to programming so I'm sure this is stupid error on my part, but I've tried rewritting the statement and same issue. Any help would be greatly appreciated.
function getSpotifySongInfo() {
//4th node argument is reserved for the song user wants to select
var query = process.argv[3];
if (query !== "") {
//could make this less repeating code by passing the song as a parameter?
spotifyClient.search({ type: 'track', query: query, limit: 1 }, function (err, data) {
if (!err) {
console.log("=============Artist==Track==Album==PreviewURL=============================");
console.log("Artist: " + data.tracks.items[0].artists[0].name);
console.log("Track: " + data.tracks.items[0].name);
console.log("Album: " + data.tracks.items[0].name);
console.log("Preview URL: " + data.tracks.items[0].preview_url);
} else {
console.log(err);
}
});
} else {
//need to make this specific for Ace of Base. For some reason it's not changing the query to reflect default song. I've tried commenting this portion out and just testing w/ a simple console.log("test") and nothing...
query = 'The Sign';
spotifyClient.search({ type: 'track', query: query, limit: 1 }, function (err, data) {
if (!err) {
console.log("=============Artist==Track==Album==PreviewURL=============================");
console.log("Artist: " + data.tracks.items[0].artists[0].name);
console.log("Track: " + data.tracks.items[0].name);
console.log("Album: " + data.tracks.items[0].name);
console.log("Preview URL: " + data.tracks.items[0].preview_url);
} else {
console.log(err);
}
});
}
}
if (query !== "") is a bad test and probably doesn't do what you want. For example:
var query = undefined;
query !== ""
// true
query = null
query !== ""
// true
You are testing for a very specific thing — an empty string — which you probably aren't getting as an argument to your function.
A better way that leads to a lot less code is to assign a value to query if none exists. You can do some thing like:
if (!query) {
query = 'The Sign'
}
Then you don't need the if/else code at all. A quick and easy way to do this is:
var query = process.argv[3] || 'The Sign'
This will either assign the value of process.argv[3] or, if that value is falsy, you'll get the default. This is a very common pattern in Javascript.

Node.js - isInteger returns false when it should return true

Straight to the point, I've got this code:
//SERVERSIDE
newSocket.on("connectOrb", function(connectingOrbId, targetOrbId)
{
if(Number.isInteger(connectingOrbId) && (Number.isInteger(targetOrbId)))
{
//FURTHER VALIDATION...
}
}
//CLIENTSIDE
socket.emit("connectOrb", parseInt(selectedOrbElement.attr("cid")), parseInt(clickedOrbElement.attr("cid")));
When I check if connectingOrbId and targetOrbId are integers on localhost, everything works fine, both conditions returns true and algorithm continues, but when I host this app on OpenShift and try to do the exact same thing, then I can't pass this validation, what could be the problem?
By the way, when I console.log(connectingOrbId) and console.log(targetOrbId) I get numbers that I should get (so it's not undefined).
EDIT:
So I've tweaked serverside code a bit, but i'm still getting same result:
newSocket.on("connectOrb", function(connectingOrbId, targetOrbId)
{
connectingOrbId = parseInt(connectingOrbId);
targetOrbId = parseInt(targetOrbId);
if(Number.isInteger(connectingOrbId) && (Number.isInteger(targetOrbId)))
{
//FURTHER VALIDATION...
}
}
EDIT2:
As Rafael asked I've checked for the type of these variables, so now the code looks like this:
newSocket.on("connectOrb", function(connectingOrbId, targetOrbId)
{
connectingOrbId = parseInt(connectingOrbId);
targetOrbId = parseInt(targetOrbId);
console.log("Connecting: "+typeof connectingOrbId);
console.log("Target: "+typeof targetOrbId);
if(Number.isInteger(connectingOrbId) && (Number.isInteger(targetOrbId)))
{
//FURTHER VALIDATION...
}
}
And console approves that both of these are Number type variables.
EDIT 3:
So as Mike helped me find out I had an old node.js version on OpenShift and a new one locally, updating an old version fixed the problem.

How to validate data with usage logic in Azure mobile service

My problem is how do I validate data. I don't know JS, so I tried do in this way:
function insert(item, user, request) {
if(typeof item.NamePlayer!=='empty') // in app default value is 'empty'
{
request.execute();
}
}
Does JS have a contain method on a table? For example I want a response to table 'NamePlayer' and not add an item with the same value.
Your condition will always be true. The operator typeof will return one of the following values: "number," "string," "boolean," "object," "function," and "undefined." - so it will never be "empty". If you want to check whether the item.NamePlayer is not empty, you can use the condition below:
if (item.NamePlayer !== '') {
// ...
}
You can also simplify the condition, which will also catch the case where the client didn't send a NamePlayer value in the input:
if (item.NamePlayer) {
// ...
}
One more thing: your script will only dealing with the "positive" case; it also needs to send a response in case the condition fails. Something like the code below:
function insert(item, user, request) {
if (item.NamePlayer) {
request.execute();
} else {
request.respond(400, 'NamePlayer is required');
}
}

Categories

Resources