Home > Back-end >  React : is it bad to use a hook in a normal function?
React : is it bad to use a hook in a normal function?

Time:11-14

So i have this react functional component :

import { createContext, useContext, useState } from 'react';
const GeneralContext = createContext();
export function GeneralContextWrapper({ children }) {
  const [userSessionExpired, setUserSessionExpired] = useState(false);
  return (
    <GeneralContext.Provider
      value={{
        userSessionExpired,
        setUserSessionExpired,
      }}
    >
      {children}
    </GeneralContext.Provider>
  );
}

export function useGeneralContext() {
  return useContext(GeneralContext);
}

I have to change the state of userSessionExpired in a normal function so i do :

const checkToken = (data) => {
  const { userSessionExpired, setUserSessionExpired } = useGeneralContext();
  if (data.status === 'fail' && data.message === 'Sessione scaduta') {
    window.location.href = '/auth/login?session=expired';
    localStorage.removeItem('jwt');
  }
  return data;
};

And i got eslint warning :

React Hook "useGeneralContext" is called in function "checkToken" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter.

where i call the checktoken function example in a fetch call :

export const call = async (url, token, data) => {
  const dataReturned = await fetch(url, {
    method: 'PUT',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(data),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => {
      return { status: 'fail', message: 'API CALL ERROR', error: err.message };
    });
  return checkToken(dataReturned);
};

I would like to know if i can ignore the warning or not?

CodePudding user response:

It's unclear how your checkToken is ever called, but you surely shouldn't be using any hooks from within an async function. In order for hooks to work properly, they have to be called in the same order every time the component renders, and if a call is originating from within an async function, it's almost guaranteed that's not going to happen.

The warning you're seeing is good advice, and you should heed it. Call your hooks within your component (or within other hooks that you create), and then if you have a function that needs the result of those hooks (in your case, a context), then pass that into the function.

  • Related