This is sort of a continuation from an earlier post I made regarding a React application that let’s a user fetch data from Goodreads’ API by typing a search query.
Since then, I’ve made a repo on GitHub that includes files for a backend api relay (which checks out when I test it on Postman), and frontend files (including components for the search bar and results).
Here’s is where I am stuck:
IMPORTANT NOTE: I’m currently experimenting with two different fetch files (fetchResults.js
and fetchResultsAlt.js
). Right now, the repo contains code that works with the fetchResultsAlt.js
file.
When I enter a search on the page and click the “Search” button, it triggers handleClick()
(seen below).
handleClick() {
const {search_query} = this.state;
if(!search_query) return;
this.setState({
loading: true,})
fetchResultsAlt(search_query)
.then((results) => {
this.setState({results, loading: false})
})
console.log(this.state.search_query)
console.log(this.state.results)
}
According to dev tools, my fetchResultsAlt()
from fetchResultsAlt.js
is getting the data I want (as seen in the console in the picture below).
But when I call fetchResultsAlt()
in index.js
, this.state.results
does not update with the fetched data; it remains an empty object (also seen below).
I also noticed that when I enter another search query (without refreshing the page first), this.state.result
is logged as undefined
.
Any thoughts or advice as to how to why this is happening? I assume it could be that the component with this.state.results
hasn’t unmounted, but I could be mistaken.