I am trying to add the below code in my React app’s index.js (Purpose is to set some Microfrontend URL dynamically from the endpoint response) before invoking App.js
I am trying as below;
import useFetch from "./utils/useFetch";
const fetchFn = useFetch();
try {
let [urls] = await fetchFn("api/urlsFromBackend", {}, "GET");
console.log("urls", urls);
window.myMfe1URL = urls.myMfe1URL;
} catch (e) {
console.error("error caught", e);
}
import('./bootstrap');
export {};
And below is my useFetch
export default function useFetch() {
const fetchData = async (url, requestData, requestType) => {
try {
} catch (error) {}
}
return fetchData;
}
However, I get an error saying
React Hook "useFetch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
is there a way to invoke this code in index.js and considering that I also have import('./bootstrap');
at the end.
2
Answers
Eslint-plugin-react-hook uses naming conventions to tell what is a hook and what is not. Anything which starts with
use
is assumed to be a hook, and thus must follow the rules of hooksYour
useFetch
function does not appear to be a hook though, because it does not call any built in hooks (eg,useState
,useEffect
). So to fix this, just change the name so that the lint rule can correctly identify it as a non-hook function:"Top level" for React Hooks, implies React function (Components or other Hooks) and not modules. React hooks are designed to be used within functional components or other custom hooks.Try out the following code:
and in the React function