API: https://developers.themoviedb.org/
const [searchQuery, setSearchQuery] = useState();
const [searchResults, setsearchResults] = useState([]);
const getSearchResults = () => {
baseService.get(`/search/multi?api_key=${API_KEY}&language=en-US&query=${searchQuery}`)
.then(data=>setsearchResults(data.results))
}
useEffect(() => {
getSearchResults()
console.log(searchResults)
}, [searchQuery])
return (
<Container>
<TextField color="primary" label="Search for anything" size="small" onChange={(e) => setSearchQuery(e.target.value)}/>
{searchResults && searchResults.map((search,key) => (
<span key={key}>{search?.title}</span>
))}
</Container>
baseservice.js is like that
import { API_URL } from "./config"
export const baseService = {
get: async (url) => {
let response = [];
await fetch(API_URL+url, {
})
.then((res) => res.json())
.then((data) => {
response = data
})
return response;
}
}
In baseService.get you’re returning response before the promise has resolved, it can be simplified to this:
export const baseService = {
get: (url) => {
return fetch(API_URL+url)
.then((res) => res.json())
}
}
This happens because you're logging searchResults inside a useEffect that has a searchQuery dependency, so it logs the first time state are set and then it doesn't log when it changes from fetch response. If you wanna log it correctly you have to add searchResults as a dependecy.
useEffect(() => {
getSearchResults()
console.log(searchResults)
}, [searchQuery, searchResults])