billysk
billysk

Reputation: 137

pass function as parameter to custom hooks

I am trying to pass a function as a parameter to custom hooks I created. The file that uses the hooks and it is it self a custom hook is this:

export const MainStore = () => {
  ...

  const checkForRefreshTokenUpdate = async () => {
    ...
  }

  const { getAssetData } = assets(checkForRefreshTokenUpdate());

  ...
}

second file:

export const assets = ( checkForRefreshTokenUpdate ) => {

  const { customAxios } = interceptedAxios(checkForRefreshTokenUpdate);

  /**
   * Fetches asset data.
   * @returns
   */
  const getAssetData = async (params) => {
    const url = buildUrl({
      baseUrl: getBaseUrl(),
      endpoint: "/api/asset",
      params
    });

    const reqOpts = {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${getAccessToken()}`
      }
    };

    return customAxios.get(url, reqOpts).then(res => { res.data });
  };

  return { getAssetData }
}

third file:

export const interceptedAxios = ( checkForRefreshTokenUpdate ) => {

  const customAxios = axios.create();

  customAxios.interceptors.request.use(async (config) => {

    if (config.url.includes(getBaseUrl()) && config.headers["Authorization"] != null) {
      await checkForRefreshTokenUpdate()
        .then((token) => {
          if (token != null) {
            config.headers["Authorization"] = `Bearer ${token}`;
          }
        });
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  });

  return { customAxios }
}

I keep getting error: ReferenceError: checkForRefreshTokenUpdate is not defined.

Is there anything wrong in syntax?

Upvotes: 0

Views: 1325

Answers (3)

Shadi Amr
Shadi Amr

Reputation: 510

Anyway beside my first answer and second one from Milos i would like to define checkForRefreshTokenUpdate inside third file (interceptedAxios), that's cleaner and less confusion because it's not used anywhere else, even if you wanna use it you can easily export it from there!

Upvotes: 0

Milos Pavlovic
Milos Pavlovic

Reputation: 1450

I agree with previous comment that first mistake you made is because you immediately called function while passing to custom "hook". So, first you need to update that part of the code as previous comment suggest to you, to pass just an reference and not the result(promise). Second mistake I spotted is this:

await checkForRefreshTokenUpdate()
    .then((token) => {
      if (token != null) {
        config.headers["Authorization"] = `Bearer ${token}`;
      }
    });

You must not use await with .then, await itself will pause the excecution until promise is resolved, so you need to update code to this:

const token = await checkForRefreshTokenUpdate();

if (token != null) {
   config.headers["Authorization"] = `Bearer ${token}`; 
}

You must either use .then syntax or async/await, you cant mix them.

Upvotes: 1

Shadi Amr
Shadi Amr

Reputation: 510

try to pass the checkForRefreshTokenUpdate function without parenthesis:

wrong :

const { getAssetData } = assets(checkForRefreshTokenUpdate());

correct :

const { getAssetData } = assets(checkForRefreshTokenUpdate);

Upvotes: 1

Related Questions