I am attempting to do a book search with the ‘bookTitle’ that users type in or select from the page. On first render ‘bookTitle’ comes back undefined, which then pulls up some random kids book called ‘undefined’. By putting the bookTitle in the dependency array of my useEffect, i expected this issue to be resolved, but now this causes it to flash the undefined book, then the desired book, and then back to undefined.
const location = useLocation()
const { data } = location.state
const [apiData, setApiData] = useState<GoogleBooks>()
const [bookTitle, setBookTitle] = useState()
const squishedTitle = data.content.title.replace(/ /g, '').toLowerCase()
useEffect(() => {
setBookTitle(squishedTitle)
fetch(`https://www.googleapis.com/books/v1/volumes?q=${bookTitle}&key=${import.meta.env.VITE_GOOGLE_API_KEY}`)
.then(res => res.json())
.then(response => setApiData(response))
.catch((err) => console.error(err))
}, [bookTitle])
I am expecting to never receive undefined when a user clicks on a book.