React Custom Hooks Circular Dependency

Viewed 446

I have two custom hooks i.e useFetch and useAuth. useAuth has all API calls methods (e.g logIn, logOut, register, getProfile etc) and they use useFetch hook method for doing API calls. useFetch also uses these methods for example logOut method when API return 401, setToken etc. So, they both need to share common methods. But that results into circular dependency and call size stack exceeded error. How to manage this

UseFetch.js

    import React, { useState, useContext } from "react";
    import { AuthContext } from "../context/authContext";
    import { baseURL } from "../utils/constants";
    import { useAuth } from "./useAuth";
    
    const RCTNetworking = require("react-native/Libraries/Network/RCTNetworking");
    
    export const useFetch = () => {

      const {token, setAuthToken, isLoading, setIsLoading, logIn, logOut} = useAuth();    
      const fetchAPI = (method, url, body, isPublic, noBaseURL) => {
        setIsLoading(true);
 
        const options = {
          method: method
          headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
          },
        };

        return fetch(url, options, isRetrying).then(() => {
         ......
         })
       ......
      };
    
      return { fetchAPI };
    };

UseAuth.js

import React, { useContext, useEffect } from "react";
import { AuthContext } from "../context/authContext";
import { useFetch } from "./useFetch";

export const useAuth = () => {
  const {
    removeAuthToken,
    removeUser,
    setUser,
    ...others
  } = useContext(AuthContext);
  const { fetchAPI } = useFetch();

  const register = (body) => {
    return fetchAPI("POST", "/customers/register", body, true);
  };

  const logIn = (body) => {
    return fetchAPI("POST", "/customers/login", body, true);
  };

  const logOut = () => {
    return (
      fetchAPI("POST", "/customers/logout")
        .catch((err) => console.log("err", err.message))
        .finally(() => {
          removeAuthToken();
          removeUser();
        })
    );
       ......
  };

  return {
    ...others,
    register,
    logIn,
    logOut,
  };
};
0 Answers
Related