Search code examples
reactjsreact-hooksnext.jsauthorizationuse-effect

React - nextjs Calling custom hook in useEffect


I'm trying to call 'useUser' custom hook, which uses useEffect & useSWR; inside useEffect of _app.tsx. But it throws,

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

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        const params = {
          p1: "someText"
          m1: "someText02",
        };
    
        const { mutateUser } = useUser({
          redirectTo: "/test",
          redirectIfFound: true,
        });
    
        try {
          const fetchUser = async () => {
            mutateUser(
              await fetchJson("/api/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(params),
              })
            );
          };
          window && fetchUser();
        } catch (error) {
          console.error("An unexpected error happened:", error);
        }
      }, []);
}

I'm not too sure why it's not working :( I first separated this code in to another function, first I thought that's why it didn't work. Soon I realized that, it wasn't the cause.

Really appreciate if anyone could help!


Solution

  • The reason is in the error message. You can't use useUser inside useEffect. You have to move it inside the body of the functional component.

    function MyApp({ Component, pageProps }) {
        const { mutateUser } = useUser({
         redirectTo: "/test",
         redirectIfFound: true,
        });
    
        useEffect(() => {
            const params = {
              p1: "someText"
              m1: "someText02",
            };
        
            try {
              const fetchUser = async () => {
                mutateUser(
                  await fetchJson("/api/login", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(params),
                  })
                );
              };
              window && fetchUser();
            } catch (error) {
              console.error("An unexpected error happened:", error);
            }
          }, []);
    }