Every time I'm trying to fetch data from the TMDB API to search for a movie, I'm getting a 'parse is undefined' error

14 views Asked by At

I'm trying to get the response from TMDB API (https://developer.themoviedb.org/reference/search-movie) for search movie query. and i observed my code more than 10 times but getting the same error :: parsed is undefined

I'm getting that searchInput from a Form Component.

function BrowseMovies() {

    let responseId = null

  const queryFunc = async (options) => {
    const response = await axios.request(options);
    responseId = response?.data?.results[0]?.id
    console.log(response.data.results)
    return response.data.results;
  };

  
  const onSubmit = (searchInput) => {
  let params = {
    query: searchInput.query,
    include_adult: searchInput.includeAdult.toString(),
    language: searchInput.language,
    primary_release_year: searchInput.year.toString(),
    page: '1',
    year: searchInput.year.toString(),
  };

  const options = {
    method: 'GET',
    url: 'https://api.themoviedb.org/3/search/movie',
    params: params,
    headers: {
      accept: 'application/json',
      Authorization: '-- Key --',
    },
  };
  queryFunc(options);
};

 const {data , isLoading , isError , error , refetch} = useQuery({
  queryKey : ['searchedMovie' , responseId],
  queryFn: queryFunc,
  enabled:false,
  refetchOnWindowFocus:false,
})
-- rendering Data --
}
1

There are 1 answers

0
quyentho On
  1. Do not mutate the responseId
  2. You put the responseId in the queryKey ['searchedMovie' , responseId] which mean it will be passed as parameters to the queryFn, which is wrong

You should do this instead:

Your fetch API:

const queryFunc = async (options) => {
    const response = await axios.request(options);
    return response.data.results;
};

Your onSubmit is to get the options, so let rename it to getOptions:

const getOptions = (searchInput) => {
  let params = {
    query: searchInput.query,
    include_adult: searchInput.includeAdult.toString(),
    language: searchInput.language,
    primary_release_year: searchInput.year.toString(),
    page: '1',
    year: searchInput.year.toString(),
  };

  const options = {
    method: 'GET',
    url: 'https://api.themoviedb.org/3/search/movie',
    params: params,
    headers: {
      accept: 'application/json',
      Authorization: '-- Key --',
    },
  };
  return options
};

This is how you construct the useQuery:

const {data , isLoading , isError , error , refetch} = useQuery({
  queryKey : ['searchedMovie'], // for simplicity, but you should choose some other unique keys, could be a  combination of multiple searchInput properties
  queryFn: () => queryFunc(getOptions(searchInput)),
  enabled:false,
  refetchOnWindowFocus:false,
})

Then you can call refetch so that react-query start fetching the data when users click the submit button:

const onSubmit = () => {
    refetch();
}