skip to Main Content

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


  1. 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 hooks

    Your 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:

    export default function createFetch() {
        const fetchData = async (url, requestData, requestType) => {
            try {
            } catch (error) {}
        }
        return fetchData;
    }
    
    // ...
    
    const fetchFn = createFetch();
    
    Login or Signup to reply.
  2. "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:

    export default function useFetch(url, requestData, requestType) {
      const [fetchData, setFetchData] = useState(null);
      useEffect(() => {
        if (url && requestData && requstType) {
          let ignore = false;
          fetch(url,
              method: requestType      
              body: requestData
            )
            .then(response => response.json())
            .then(json => {
              if (!ignore) {
                setFetchData(json);
              }
            });
          return () => {
            ignore = true;
          };
        }
      }, [url, requestData, requestType]);
      return fetchData;
    }
    

    and in the React function

    import useFetch from 'pathToUseFetch/useFetch';
        
    const SomeReactFunction () {
      const fetchedData = useFetch(
        url,
        requestData,
        requestType 
      );
      ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search