'Reactjs Empty State when Page Load

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;
    }
  }

1.Picture is when page load. enter image description here

2.Picure is when entry search term. After the entry search:



Solution 1:[1]

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())
    }
  }

Solution 2:[2]

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])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 helloitsjoe
Solution 2 arthurg