So I have 3 functions below. One containing calls to the two (getBooks), which are getting requests. I set my state (isLoading) to true before the calls and then to true after the calls. This is to also make sure that the data is properly loaded. However the state is not updating so, therefore, my data from the get request is invalid. The callbacks in my setstate work in my other components, so I am confused. Below are my 3 functions.
import React from 'react';
import ReactDOM from 'react-dom';
import SidePane from './SidePane.js';
import HomeNavBar from './HomeNavBar.js';
import axios from 'axios';
import qs from 'qs';
import Loading from './Loading.js';
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
bookSearch: "",
bookSearchResults: [],
bookSearchFound: false,
isLoading: false
};
this.handleSearch = this.handleSearch.bind(this);
this.alertBookName = this.alertBookName.bind(this);
this.getBooksFromIsbn = this.getBooksFromIsbn.bind(this);
this.getBooks = this.getBooks.bind(this);
axios.defaults.withCredentials = true;
}
changeBookName = (e) => {
var bookName = e.target.value;
bookName = bookName.split(' ').join('+');
this.setState({bookSearch: bookName})
}
getBooksFromIsbn(isbns){
var books = [];
axios
.get('http://localhost:9000/api/getBooksFromIsbn',
{
params: {
books: JSON.stringify(isbns)
}
})
.then(res =>
{
console.log(res.data);
books = res.data;
})
.catch(error => {
console.log(error.response);
});
}
getBooks(){
this.setState({
isLoading: true
},
function(){console.log("setState completed", this.state)}
);
var bookResults = this.handleSearch();
var books = this.getBooksFromIsbn(bookResults);
this.setState({
isLoading: false
},
function(){console.log("setState completed", this.state)}
);
this.props.setBookSearchResults(books);
}
handleSearch(){
var bookResults = [];
var url = 'http://localhost:9000/api/getOpenLibrarySearch';
axios
.get(url,
{
params: {
bookSearch: this.state.bookSearch
}
})
.then(res =>
{
//this.setState({bookSearchResults: res.data});
for(var i=0; i < res.data.docs[i].isbn.length; i++){
bookResults = bookResults.concat(res.data.docs[i].isbn);
}
console.log(bookResults);
})
.catch(error => {
console.log(error.response);
});
return bookResults;
}
render(){
if(this.state.isLoading == false){
return(
<div>
<HomeNavBar authToken = {this.props.authToken} email = {this.props.email} />
<SidePane changeBookName = {this.changeBookName} handleSearch = {this.getBooks} />
</div>
)
}
else
{
return <Loading />;
}
}
}