I am working with an array of phrases and in the class App
I have in componentDidMount
it setState
and all that but my function selectQuoteIndex
returns undefined. In quotesData.js I have an array of objects with two properties, one is quote and the other is author, then in that same file I have a method getQuotes
that returns the array of quotes.
import React, { Component } from 'react';
import { random } from 'lodash';
import { getQuotes } from './services/quotesData';
import Button from './components/button';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
quotes: [],
selectedQuoteIndex: null
}
this.selectQuoteIndex = this.selectQuoteIndex.bind(this);
}
componentDidMount() {
this.setState({ quotes: getQuotes(), selectedQuoteIndex: this.selectQuoteIndex() })
}
selectQuoteIndex() {
if(!this.state.quotes.length) {
return;
}
return random(0, this.state.quotes.length - 1);
}
render() {
console.log(this.state.selecetedQuoteIndex);
return (
<div className="App" id = "quote-box">
<Button buttonDisplayName = "Next Quote" clickHandler = {this.selectQuoteIndex} />
</div>
);
}
}
export default App;
This code is the cause
When the component is mounted it is initialized with a state that has a property
quotes
that is an empty array and therefore thelength === 0
So if we run your code we have to
When you deny the
0
it returnstrue
because the0
is a valuefalsey
and therefore the onereturn;
that is equivalent to is executedreturn undefined;
since in javascript the functions always return something and since you do not specify anything that something isundefined
.I think your code is fixed if you remove the negation:
Not putting a
return
in some conditions is the same as writing that'sreturn undefined
why I didn't write it.