6

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,
  };
};
artsnr
  • 952
  • 1
  • 10
  • 27

1 Answers1

0

Simply carry the logOut logic out of the useAuth to your helpers or utils. Use that logic both in useAuth's logOut method and useFetch's 401 condition. Since logout method is the only thing required from useAuth, you can just remove the useAuth hook and use useContext(AuthContext) to get other props.

Enes Toraman
  • 261
  • 2
  • 8