user11367277
user11367277

Reputation:

How is this condition false?

I am building a web app in Typescript with React, I have an if statement in my componentDidMount()in order to change the state of a component and rerender it under certain conditions. But I somehow can't understand why the expression keeps returning false. Anyone got an idea or explanation?

componentDidMount() {
if (this.props.altSrc != this.state.currentSrc && this.state.errored == true) {
  this.setState({...this.state, errored: false, currentSrc: this.props.altSrc})
  } 
}

The value of the variables is as follows:

The way I see it the outcoe should be true, since the two strings are not equal to eacht other and return true and when error is true it should return as well. So then we have true && true => true.

So I am asking what am I missing here in the condition of the if statement?

Background

What this code should do is render an image to the screen but when the image is not found it should replace the image(currentSrc) with an alternative image(altSrc). When the alt. image is not found the render method return null. Everything works fine I managed to get notified when the image does not load and than set errored to true, only the condition of the if is giving trouble.

Upvotes: 0

Views: 188

Answers (1)

Fenton
Fenton

Reputation: 250982

Sometimes old-skool is the way... what's your output?

console.log(this.props.altSrc, typeof this.props.altSrc, this.state.currentSrc, typeof this.state.currentSrc, (this.props.altSrc != this.state.currentSrc));
console.log(this.state.errored, typeof this.state.errored, this.state.errored == true);

if (this.props.altSrc != this.state.currentSrc && this.state.errored == true) {
    console.log('WE MADE IT INTO THE CONDITION');
    this.setState({...this.state, errored: false, currentSrc: this.props.altSrc})
} 

My simulation says that either the values are different to what you expect, or there is a bit of type juggling funk going on.

const altSrc = 'abcde' as string;
const currentSrc = 'fghij' as string;
const errored = true as boolean;

console.log(altSrc, typeof altSrc, currentSrc, typeof currentSrc, (altSrc != currentSrc));
console.log(errored, typeof errored, errored == true);

if (altSrc != currentSrc && errored == true) {
    console.log('WE MADE IT INTO THE CONDITION');
} 

OUTPUT:

abcde string fghij string true
true boolean true
WE MADE IT INTO THE CONDITION

Upvotes: 0

Related Questions