0

The use case

I am writing a piece of code searching for movies' deatils into the https://themoviedb.org

the code is written in React 17.0.2 using yarn, visual studio code.

The issue

I am calling a function, from a useEffect, that will generate a json file from the result of the call to TheMovieDB

I got the following error, could you help me? **Error: Invalid hook call. Hooks can only be called inside of the body of a function component. **

Thank you in advance for the time you will invest on this issue

useEffect in browser_movie_db.js

 useEffect(() => {
    if (slideRows.length > 0 && searchTerm.length > 2) {
      const searchResult = searchInTheMovieDB(category, searchTerm);
      if (searchResult.results.length > 0) {
        setSlideRows(searchResult);
      } else {
        setSlideRows(slides[category]);
      }
    } else {
      setSlideRows(slides[category]);
      console.log("slideRows", slideRows);
    setSlideRows(slides[category]);
  }, [category, searchTerm, slideRows, slides, theMovieDBApikey]);
    }

searchInTheMovieDB function in selection-filter-themoviedb.js

export function searchInTheMovieDB(media_type, query) {
  let result = {};
  if (media_type === "tv") {
    result = {
      tv: [
        {
          title: `${media_type} search result`,
          data: GetSearch(media_type, query),
        },
      ],
    };
  } else {
    result = {
      movie: [
        {
          title: `${media_type} search result`,
          data: GetSearch(media_type, query),
        },
      ],
    };
  }
  return result;
}

GetSearch function in selection-filter-themoviedb.js

export function GetSearch(media_type, query) {
  const [content, setContent] = useState([]);
  useEffect(() => {

    console.log("GetSearch", `${endpoint.Search}/${media_type}?query=${query}`);
    api
      .get(`${endpoint.Search}/${media_type}`, {
        params: {
          api_key,
          query,
        },
      })
      .then((res) => {
        setContent(res.data.results);
      })
      .catch((error) => {
        console.error("error.message", error.message);
      });
  }, [media_type, query]);
  return { [media_type]: content };
}

Error Invalid hook call.

Error: Invalid hook call. Hooks can only be called inside of the body of a function component

Abdelkrim
  • 2,048
  • 5
  • 30
  • 44
  • 1
    Every function that calls a hook which is not a component may be named `useXYZ` (is itself a hook). Proceed recursively until you find a call to a hook which is not in a hook and not in a component. – Jonas Wilms Apr 18 '21 at 12:38
  • Also have a look at https://stackoverflow.com/questions/53895455/how-does-javascript-mechanism-behind-react-hooks-work/53895655#53895655 – Jonas Wilms Apr 18 '21 at 12:40
  • Hooks simply don't make sense outside of a (function) component, as they're intimately connected with the component lifecycle and other React-specific features. Not only are you not allowed to call them inside an unrelated function, there's absolutely no reason to want to. You seem to be trying to use state/effect Hooks inside a function that makes an API request, and I think you're misunderstanding asynchronous JS code as well as misunderstanding Hooks - for the async part, see [here](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Robin Zigmond Apr 18 '21 at 12:54

1 Answers1

0

the solution

I have increased the amount of useEffects to identify the process :

  1. the *searchTerm changes
  2. then, the web services is called
  3. eventually, the slideRows variable is set with a new content

PS: I have created an async function fetching the data from the webservice


    const [searchResults, setSearchResults] = useState([]);

    import axios from "axios";
    const api = axios.create({ baseURL: BASE_URL });

    async function getSearch(media_type, query) {
    api
      .get(`${endpoint.Search}/${media_type}`, {
        params: {
          api_key,
          query,
        },
      })
      .then((res) => {
        setSearchResults(res.data.results);
      })
      .catch((error) => {
        console.error("error.message", error.message);
      });

  }

  useEffect(() => {
    if (searchResults.length > 0) {
      setSlideRows({
        tv: [
          {
            title: `${category} search result`,
            data: searchResults,
          },
        ],
      });
    }
  }, [category, searchResults]);

  useEffect(() => {
    if (slideRows.length > 0 && searchTerm.length > 2) {
      getSearch(category, searchTerm);
    } else {
      setSlideRows(slides[category]);
    }
  }, [searchTerm, slides]);

  useEffect(() => {
    if (searchResults.length > 0 && searchResults.results?.length > 0) {
      setSlideRows(searchResults);
    } else {
      setSlideRows(slides[category]);
    }

    setSlideRows(slides[category]);
  }, [searchResults]);
Abdelkrim
  • 2,048
  • 5
  • 30
  • 44